Десахаризация for
map и flatMap
«Десахаризация for» — бесплатный урок Scala for Backend Engineering & Functional Programming на CoddyKit. Это урок 1 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Scala for Backend Engineering & Functional Programming, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Scala for Backend Engineering & Functional Programming содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
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.
Часто задаваемые вопросы
Урок «Десахаризация for» бесплатный?
Да — полный текст урока «Десахаризация for» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Scala for Backend Engineering & Functional Programming, подпишись на CoddyKit PRO. Курс Scala for Backend Engineering & Functional Programming содержит 4 уроков всего.
Чему я научусь в уроке «Десахаризация for»?
map и flatMap Ты практикуешь Scala for Backend Engineering & Functional Programming с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать Scala for Backend Engineering & Functional Programming?
Предыдущий опыт не требуется. Scala for Backend Engineering & Functional Programming на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 1 из 4.
Сколько времени занимает урок «Десахаризация for»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке Scala for Backend Engineering & Functional Programming?
Да. Каждый урок Scala for Backend Engineering & Functional Programming включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.