Desugaring for
map and flatMap.
Desugaring for is a free Scala for Backend Engineering & Functional Programming lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Scala for Backend Engineering & Functional Programming learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
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)
}
}The yield keyword
The yield keyword tells Scala to collect the results into a new collection of the same kind.
Without yield, the for-comprehension performs a side effect for each element and returns Unit (it becomes foreach).
object Main {
def main(args: Array[String]): Unit = {
// No yield: side effect only
for (x <- List("a", "b")) println(x)
// With yield: builds a new List
val upper = for (x <- List("a", "b")) yield x.toUpperCase
println(upper)
}
}Two generators become flatMap + map
With two or more generators, the outer ones become flatMap and the innermost becomes map.
for (x <- xs; y <- ys) yield f(x, y)- becomes
xs.flatMap(x => ys.map(y => f(x, y)))
object Main {
def main(args: Array[String]): Unit = {
val pairs = for {
x <- List(1, 2)
y <- List("a", "b")
} yield (x, y)
println(pairs)
}
}Seeing the equivalent flatMap
Here we write the same logic both ways. Proving they are equal demonstrates that for-comprehensions add no magic, only readability.
object Main {
def main(args: Array[String]): Unit = {
val sugar = for {
x <- List(1, 2)
y <- List(10, 20)
} yield x + y
val desugared = List(1, 2).flatMap(x => List(10, 20).map(y => x + y))
println(sugar)
println(sugar == desugared)
}
}Why flatMap for the outer generator
Each outer element produces a whole collection of inner results. If we used map for the outer generator, we would get a nested collection like List(List(...), List(...)).
flatMap flattens those nested lists into one flat result.
object Main {
def main(args: Array[String]): Unit = {
val nested = List(1, 2).map(x => List(10, 20).map(y => x + y))
val flat = List(1, 2).flatMap(x => List(10, 20).map(y => x + y))
println(nested)
println(flat)
}
}for without yield is foreach
A for-loop with no yield is rewritten into foreach. It runs the body for its side effects and produces Unit.
for (x <- xs) doSomething(x)- becomes
xs.foreach(x => doSomething(x))
object Main {
def main(args: Array[String]): Unit = {
val r: Unit = for (x <- List(1, 2, 3)) print(x + " ")
println()
println("Return type is Unit")
}
}Result type follows the first generator
The type of the result is determined by the first generator's collection. A for over a List yields a List; over a Set, a Set; over an Option, an Option.
object Main {
def main(args: Array[String]): Unit = {
val fromList = for (x <- List(1, 2, 2, 3)) yield x
val fromSet = for (x <- Set(1, 2, 2, 3)) yield x
println(fromList)
println(fromSet)
}
}Binding values with =
Inside a for-comprehension you can bind intermediate values with =. This avoids recomputation and improves readability.
It desugars into a map that carries the extra value along in a tuple.
object Main {
def main(args: Array[String]): Unit = {
val result = for {
x <- List(1, 2, 3)
doubled = x * 2
} yield doubled + 1
println(result)
}
}Works on any type with map/flatMap
Because the desugaring only relies on map and flatMap, for-comprehensions work on any type that defines those methods: Option, Either, Try, Future, and your own classes.
object Main {
def main(args: Array[String]): Unit = {
val combined = for {
a <- Some(2)
b <- Some(3)
} yield a * b
println(combined)
}
}Readability is the real win
Compare a deeply nested flatMap/map chain to a clean for-comprehension. They compile to the same thing, but the for version reads top-to-bottom like a recipe.
object Main {
def main(args: Array[String]): Unit = {
val chained = List(1, 2).flatMap(a => List(3, 4).map(b => a * b))
val readable = for {
a <- List(1, 2)
b <- List(3, 4)
} yield a * b
println(chained == readable)
}
}Quick Check
How does the compiler desugar a for-comprehension with two generators and a yield?
Recap
You learned how for-comprehensions desugar:
- One generator +
yield→map - Multiple generators +
yield→flatMap(outer) +map(inner) - No
yield→foreachreturningUnit val =bindings add intermediate values- The result type follows the first generator
Any type with map and flatMap can be used in a for-comprehension.
Frequently asked questions
Is the “Desugaring for” lesson free?
Yes — the full text of “Desugaring for” is free to read here on the web, and the Scala for Backend Engineering & Functional Programming course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Scala for Backend Engineering & Functional Programming course, upgrade to CoddyKit PRO.
What will I learn in “Desugaring for”?
map and flatMap. You practise Scala for Backend Engineering & Functional Programming with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Scala for Backend Engineering & Functional Programming?
No prior experience is required. Scala for Backend Engineering & Functional Programming on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Desugaring for” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Scala for Backend Engineering & Functional Programming lesson?
Yes. Every Scala for Backend Engineering & Functional Programming lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.