← Back to Scala Course | Chapter 11: Error Handling & Option | Lesson 7 of 7

for Comprehension with Option

for Comprehension with Option

A for comprehension works directly with Option values, short-circuiting to None as soon as any generator produces None, and yielding Some(result) only if every step succeeded. This desugars to chained .flatMap calls, the same mechanism covered for List earlier, just applied to Option instead. It's a clean way to combine several optional values without a pyramid of nested .flatMap/.map calls or pattern matches.

Note: A for comprehension over multiple Options short-circuits to None the moment any one of them is None -- no explicit checks needed.

Example: for Comprehension with Option

markup
object Main extends App {
  val a: Option[Int] = Some(5)
  val b: Option[Int] = Some(10)
  val c: Option[Int] = None

  val sumAB = for {
    x <- a
    y <- b
  } yield x + y

  val sumWithMissing = for {
    x <- a
    y <- c
  } yield x + y

  println(sumAB)
  println(sumWithMissing)
}
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.