0PricingLogin
Scala for Backend Engineering & Functional Programming · Lesson

Composing Either

map and flatMap.

Composing Computations

Real programs chain several fallible steps: parse, validate, look up, compute. Either lets you compose these so that the first failure short-circuits the whole chain.

The tools are map, flatMap, and for-comprehensions.

flatMap Sequences Eithers

flatMap applies a function that itself returns an Either. If the receiver is Left, the function is never called and the Left propagates.

object Main {
  def positive(n: Int): Either[String, Int] =
    if (n > 0) Right(n) else Left("not positive")

  def main(args: Array[String]): Unit = {
    val r = Right(5).flatMap(positive)
    val l = Right(-1).flatMap(positive)
    println(r)
    println(l)
  }
}

All lessons in this course

  1. Either for Errors
  2. Try, Success, Failure
  3. Composing Either
  4. Converting Between Types
← Back to Scala for Backend Engineering & Functional Programming