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