0Pricing
Scala for Backend Engineering & Functional Programming · Lesson

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

  1. Avoiding null
  2. map and flatMap on Option
  3. getOrElse and fold
  4. Option in for-comprehensions
← Back to Scala for Backend Engineering & Functional Programming