for Comprehension with Option
In this page:
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
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: