0Pricing
Scala for Backend Engineering & Functional Programming · Lesson

Using with Option and Future

Monadic chaining.

Beyond collections

For-comprehensions are not limited to lists. Any type that provides map and flatMap can be used, including Option, Either, Try, and Future. This is called monadic chaining.

object Main {
  def main(args: Array[String]): Unit = {
    val sum = for {
      a <- Some(10)
      b <- Some(20)
    } yield a + b
    println(sum)
  }
}

Option short-circuits on None

With Option, the comprehension produces a result only if every generator is Some. If any is None, the whole result is None and later steps are skipped.

object Main {
  def main(args: Array[String]): Unit = {
    val ok = for {
      a <- Some(2)
      b <- Some(3)
    } yield a * b

    val missing = for {
      a <- Some(2)
      b <- None: Option[Int]
    } yield a * b

    println(ok)
    println(missing)
  }
}

All lessons in this course

  1. Desugaring for
  2. Filtering with if
  3. Multiple Generators
  4. Using with Option and Future
← Back to Scala for Backend Engineering & Functional Programming