For Comprehensions
For-comprehensions make chains of flatMap and map read like simple step-by-step code.
On this page · 5 min · Intermediate
On this page
- In simple words
- Learning objectives
- Explanation
- Code example
- Step by step
- Real-world use
- Common mistakes
- Best practices
- Remember this
- Practice exercise
- Mini quiz
- Related topics
- My notes
- Reading time
- 5 min
- Difficulty
- Intermediate
- Updated
- Oct 30, 2026
Related tutorials
In simple words#
A for-comprehension is a recipe: “get flour, then get eggs, then mix”. If any step fails (no eggs), the whole recipe stops — no need to check after every step.
- Generator
- x <- container takes a value out.
- yield
- Builds the final result.
- Desugaring
- The compiler rewrites it into flatMap/map/withFilter.
Learning objectives#
- Write for-comprehensions with yield
- Combine several generators
- Chain Option and Either
- Understand desugaring
Explanation#
for { a <- xs; b <- ys } yield (a, b) produces every combination for lists.
With Option/Either, the chain stops at the first None/Left.
Filters: if conditions; definitions: name = expression.
It is syntax sugar: for a <- x; b <- y yield f(a, b) becomes x.flatMap(a => y.map(b => f(a, b))).
Code example: Combining lookups#
case class User(id: Int, name: String, cityId: Int)
val users = Map(1 -> User(1, "Asha", 10), 2 -> User(2, "Ravi", 99))
val cities = Map(10 -> "Pune")
def cityOf(userId: Int): Option[String] =
for
user <- users.get(userId)
city <- cities.get(user.cityId)
yield s"${user.name} lives in $city"
println(cityOf(1))
println(cityOf(2)) // city missing
println(cityOf(3)) // user missing
val combos = for
size <- List("S", "M")
color <- List("Red", "Blue")
if !(size == "S" && color == "Blue")
sku = s"$size-$color"
yield sku
println(combos)
Some(Asha lives in Pune) None None List(S-Red, M-Red, M-Blue)
This example is illustrative. Copy or download it and run it in your own environment; the expected output is shown above.
Step-by-step explanation#
- Two Option lookups are chained.
- Any None makes the whole result None.
- List generators produce combinations.
- A filter removes one combo; = defines sku.
Real-world use case#
Services chain “find user → find account → check balance” with a for-comprehension over Either or Future.
Common mistakes#
All generators must be the same type (e.g. all Option). Convert with toRight, toOption, etc.
Rewrite them as a for-comprehension for readability.
Best practices#
- Use for chains of dependent steps
- Keep one container type
- Name intermediate values
- yield the final shape
Remember this#
<- takes out, yield puts back.
First None/Left stops everything.
Sugar for flatMap + map.
Practice exercise#
Your task: Use a for-comprehension to add two Option[Int] values.
Show solution
def add(a: Option[Int], b: Option[Int]) =
for x <- a; y <- b yield x + y
Mini quiz#
A for-comprehension over Options returns None when…
Want more? Practise all Scala MCQs · Scala interview questions
My notes#
Saved in this browser.