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
- Either for Errors
- Try, Success, Failure
- Composing Either
- Converting Between Types