0PricingLogin
Scala for Backend Engineering & Functional Programming · Lesson

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)
  }
}

All lessons in this course

  1. List, Vector, Set, Map
  2. Transformations
  3. Folding and Reducing
  4. Grouping and Sorting
← Back to Scala for Backend Engineering & Functional Programming