Option in for-comprehensions
Chaining options.
Chaining Options Cleanly
Chaining several flatMap and map calls can get hard to read. Scala's for-comprehension offers a cleaner syntax for the same thing.
It is sugar that the compiler rewrites into flatMap and map calls.
Basic for-comprehension
Inside for { ... } yield ..., each x <- option extracts the value if present. The yield builds the final result.
If every Option is a Some, you get a Some of the result.
object Main {
def main(args: Array[String]): Unit = {
val a: Option[Int] = Some(3)
val b: Option[Int] = Some(4)
val sum = for {
x <- a
y <- b
} yield x + y
println(sum)
}
}All lessons in this course
- Avoiding null
- map and flatMap on Option
- getOrElse and fold
- Option in for-comprehensions