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.
In this page:
Syntax
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
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)
}
Login to try C/C++/Java/PHP code in the editor
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
- Expecting a
foroverOptionvalues to give a plain number, when it givesOption[Int]. - Mixing
OptionandListgenerators in onefor, which gives a type error. - Assuming the code continues after a
None, when the whole comprehension givesNoneas soon as one generator isNone.
Chapter Summary
OptionwithSomeandNonerepresents values that may be missing.mapandgetOrElsework withOptionvalues.TrywithSuccessandFailure,Either, and for comprehensions handle errors.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: