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

for Comprehension with Option

A for comprehension can chain several Option boxes and stops if any of them is empty. It is like a treasure hunt where you keep going only while each clue is found.
Syntax
scala
val result = for {
  a <- option1
  b <- option2
} yield expression

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)
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Expecting a for over Option values to give a plain number, when it gives Option[Int].
  2. Mixing Option and List generators in one for, which gives a type error.
  3. Assuming the code continues after a None, when the whole comprehension gives None as soon as one generator is None.
Chapter Summary
  • Option with Some and None represents values that may be missing.
  • map and getOrElse work with Option values.
  • Try with Success and Failure, Either, and for comprehensions handle errors.
🔒

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.