Transformations
map, filter, flatMap.
Transforming collections
Scala collections are immutable by default. Instead of mutating them, you transform them into new collections using methods like map, filter, and flatMap.
object Main {
def main(args: Array[String]): Unit = {
val nums = List(1, 2, 3, 4)
val doubled = nums.map(_ * 2)
println(nums)
println(doubled)
}
}map: transform every element
map applies a function to each element and returns a new collection of the same size. The element type may change.
object Main {
def main(args: Array[String]): Unit = {
val words = List("scala", "rocks")
val lengths = words.map(_.length)
println(lengths)
}
}