for desugaren
map und flatMap
for desugaren ist eine kostenlose Scala for Backend Engineering & Functional Programming-Lektion auf CoddyKit. Dies ist Lektion 1 von 4. Du kannst die komplette Lektion unten kostenlos lesen – dann übst du sie direkt im Browser mit einem integrierten Code-Editor und einem KI-Tutor rund um die Uhr. Sie ist Teil des Scala for Backend Engineering & Functional Programming-Lernpfads, und dein Fortschritt wird über Web und CoddyKit-App synchronisiert. Der Scala for Backend Engineering & Functional Programming-Kurs umfasst insgesamt 4 Lektionen.
Teile dieser Lektion wurden noch nicht übersetzt und werden auf Englisch angezeigt.
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.
Häufig gestellte Fragen
Ist die Lektion „for desugaren“ kostenlos?
Ja — der vollständige Text von „for desugaren“ ist hier im Web kostenlos zu lesen. Um sie interaktiv zu üben (integrierter Code-Editor und 24/7 KI-Tutor) und den Rest des Scala for Backend Engineering & Functional Programming-Kurses freizuschalten, upgrade auf CoddyKit PRO. Der Scala for Backend Engineering & Functional Programming-Kurs umfasst insgesamt 4 Lektionen.
Was lerne ich in „for desugaren“?
map und flatMap Du übst Scala for Backend Engineering & Functional Programming mit praktischem Code, den du direkt im Browser ausführst, und ein 24/7 KI-Tutor beantwortet deine Fragen während du die Lektion bearbeitest.
Brauche ich Erfahrung, um Scala for Backend Engineering & Functional Programming zu starten?
Keine Vorkenntnisse erforderlich. Scala for Backend Engineering & Functional Programming auf CoddyKit ist für Anfänger bis fortgeschrittene Lernende strukturiert, sodass du hier starten oder von Anfang an beginnen und in deinem eigenen Tempo voranschreiten kannst. Dies ist Lektion 1 von 4.
Wie lange dauert die Lektion „for desugaren“?
Die meisten CoddyKit-Lektionen dauern etwa 5–10 Minuten. Jede ist kompakt und interaktiv, sodass du stetig Fortschritte machst und genau dort weitermachst, wo du aufgehört hast – im Web und in der App.
Kann ich in dieser Scala for Backend Engineering & Functional Programming-Lektion Code schreiben und ausführen?
Ja. Jede Scala for Backend Engineering & Functional Programming-Lektion enthält einen integrierten Code-Editor, sodass du echten Code direkt in deinem Browser schreibst und ausführst und sofort KI-Feedback erhältst — ohne lokale Einrichtung erforderlich.