0PricingLogin
Scala for Backend Engineering & Functional Programming · Lesson

Either for Errors

Left and Right.

Why Either?

Either represents a value that can be one of two possibilities. It is the idiomatic way to model computations that may fail with information about the failure.

  • Left conventionally holds the error.
  • Right conventionally holds the success value.

Unlike Option, which only tells you something is missing, Either tells you what went wrong.

The Either Type

Either[A, B] is a sealed trait with two subtypes: Left[A] and Right[B].

The mnemonic: Right is right (correct), Left is the error. This convention lets map and flatMap operate on the success side automatically.

val ok: Either[String, Int] = Right(42)
val err: Either[String, Int] = Left("boom")
println(ok)
println(err)

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