liveBook · Manning

Either

As explained in Functional Programming in Scala, Second Edition

The Either monad is the monadic structure formed by sequencing computations that may produce a left or right result.

Either represents a computation that produces one of two typed outcomes. By convention, Left carries failure information and Right carries success, allowing errors to remain ordinary values rather than thrown exceptions. section 4.4 section 4.6

enum Either[+E, +A]:
  case Left(value: E)
  case Right(value: A)

The two constructors make the alternative outcomes explicit: E describes the error and A describes the successful result. section 4.4

Unlike Option, Either preserves a reason for failure. An empty mean can return Left("mean of empty list!") while a valid input returns Right(xs.sum / xs.length); exceptions can likewise be captured as Left values. section 4.4

Either’s combinators sequence successful computations while propagating the first Left:

  • map transforms the Right value and leaves Left unchanged. section 4.6
  • flatMap chains functions returning Either, stopping subsequent work after failure. section 4.6
  • orElse supplies a fallback after failure, and map2 combines two successful results. section 4.6
  • sequence and traverse collect lists of successful results while retaining an error outcome. section 4.6

Parsing and validation

A for-comprehension can parse an age and ticket count with Either.catchNonFatal, then calculate an insurance quote only when both conversions succeed. Constructors for Name and Age similarly return validation errors or validated values, and Person.make combines them with map2. section 4.4 section 4.4

The design replaces hidden, untyped control flow with explicit, referentially transparent results. Higher-order functions centralize propagation and recovery without requiring every call site to handle exceptions manually. section 4.0 section 4.5

How Functional Programming in Scala, Second Edition covers it

How deep it goes
Defines constructors, implements core combinators, and applies them to parsing, validation, sequencing, and traversal.
Examples
Uses empty-list means, safe division, exception capture, insurance-quote parsing, and Name-Age-Person validation.
What it assumes
Assumes basic functional programming and Scala while developing Either from its constructors through practical error-handling patterns.
What you can do after
Builds composable error-handling functions with map, flatMap, map2, sequence, traverse, and for-comprehensions.
How it connects
Connects Either to exceptions, Option, Try, Validated, monads, for-comprehensions, higher-order functions, and algebraic data types.

Also explained in

Compare how 4 books explain Either →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Functional Programming in Scala, Second Edition. The section links point to the parts of the book it draws on.