Scala by Example: Collections
Working with Scala collections library through this sample code demonstrating immutable List, Map, and Set data structures, functional operations like map filter and reduce, getOrElse for safe access, unique element enforcement, and for-comprehension syntax for transformations.
Code
// List (Immutable by default)
val nums = List(1, 2, 3, 4, 5)
// Functional operations
val doubled = nums.map(_ * 2) // List(2, 4, 6, 8, 10)
val evens = nums.filter(_ % 2 == 0) // List(2, 4)
val sum = nums.reduce(_ + _) // 15
// Map (Immutable)
val colors = Map("red" -> "#FF0000", "green" -> "#00FF00")
val redHex = colors("red") // "#FF0000"
val blueHex = colors.getOrElse("blue", "#000000")
// Set (Unique elements)
val unique = Set(1, 1, 2, 3) // Set(1, 2, 3)
// Sequence comprehension (for-yield)
val squares = for {
n <- nums
if n > 2
} yield n * n // List(9, 16, 25)Explanation
Scala's collections library is robust and favors immutability by default. The standard List, Map, and Set are immutable, meaning operations like adding or removing elements return a new collection rather than modifying the existing one. This immutability makes reasoning about state much easier, especially in concurrent applications, and eliminates entire classes of bugs related to unexpected mutations. Mutable versions exist in the scala.collection.mutable package when needed for performance-critical code.
Collections provide powerful higher-order functions like map, filter, reduce, fold, flatMap, and many others. These allow you to manipulate data declaratively rather than imperatively. Instead of writing explicit loops to transform lists, you chain these methods together to describe the transformation pipeline. For example, nums.filter(_ % 2 == 0).map(_ * 2) filters even numbers and doubles them in a clear, composable way.
Scala supports for-comprehensions using for and yield keywords, which provide syntactic sugar for chaining map, flatMap, and filter operations. This allows you to write complex data transformations in a readable, imperative-looking style that is actually functional under the hood. For-comprehensions are particularly powerful when working with nested collections or multiple data sources, making code that would be complex with explicit method chaining much more readable.
Code Breakdown
nums.map(_ * 2) creates new list with every element multiplied by 2.getOrElse provides default value if key doesn't exist, avoiding exceptions.Set automatically removes duplicates, keeping only unique elements.for ... yield transforms collection; equivalent to nums.filter(...).map(...).
