0Pricing
Scala for Backend Engineering & Functional Programming · Lesson

Desugaring for

map and flatMap.

What is a for-comprehension?

A for-comprehension in Scala is special syntax for working with collections and other container types. It looks like an imperative loop, but it is really syntactic sugar that the compiler rewrites into calls to map, flatMap, filter, and foreach.

Understanding the desugaring helps you reason about any for-comprehension, even over custom types.

object Main {
  def main(args: Array[String]): Unit = {
    val result = for (x <- List(1, 2, 3)) yield x * 10
    println(result)
  }
}

A single generator becomes map

When a for-comprehension has exactly one generator and uses yield, the compiler rewrites it into a single map call.

  • for (x <- xs) yield f(x)
  • becomes xs.map(x => f(x))
object Main {
  def main(args: Array[String]): Unit = {
    val a = for (x <- List(1, 2, 3)) yield x + 1
    val b = List(1, 2, 3).map(x => x + 1)
    println(a == b)
  }
}

All lessons in this course

  1. Desugaring for
  2. Filtering with if
  3. Multiple Generators
  4. Using with Option and Future
← Back to Scala for Backend Engineering & Functional Programming