Scala · Working with Data

For Comprehensions

For-comprehensions make chains of flatMap and map read like simple step-by-step code.

Intermediate 5 min Lesson 12 of 25Examples use Scala 3 (3.3 LTS or newer) with sbt or scala-cli.
Before you start:Option and Either
0/25 in Scala
On this page · 5 min · Intermediate

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#

ScalaCombining lookups Illustrative
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)
Expected output
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#

  1. Two Option lookups are chained.
  2. Any None makes the whole result None.
  3. List generators produce combinations.
  4. 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#

Mixing container types

All generators must be the same type (e.g. all Option). Convert with toRight, toOption, etc.

Deep nested flatMaps

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
Scala Illustrative
def add(a: Option[Int], b: Option[Int]) =
  for x <- a; y <- b yield x + y

Mini quiz#

For Comprehensions quizMultiple choice Question 1 of 1

A for-comprehension over Options returns None when…

Score so far: 0/0

Want more? Practise all Scala MCQs · Scala interview questions

My notes#

Saved in this browser.

Progress is saved in this browser. Sign in to sync.