← Back to Scala Course | Chapter 11: Error Handling & Option | Lesson 6 of 7

The Either Type

In this page:

  1. The Either Type

The Either Type

Either[L, R] represents one of two possible outcomes: a Left(value) (conventionally an error) or a Right(value) (conventionally a success). Unlike Try, which is specifically for exceptions, Either lets you use any type you want for the error case, such as a descriptive error message or custom error type. Pattern matching, or the modern .map/.flatMap methods (which operate on the Right side by convention), are the standard ways to work with it.

Note: By convention, Right represents success and Left represents failure -- a helpful mnemonic is that Right also means "correct".

Example: The Either Type

markup
object Main extends App {
  def divide(a: Int, b: Int): Either[String, Int] = {
    if (b == 0) Left("Cannot divide by zero")
    else Right(a / b)
  }

  val result1 = divide(10, 2)
  val result2 = divide(10, 0)

  println(result1)
  println(result2)

  result2 match {
    case Right(value) => println(s"Result: $value")
    case Left(error) => println(s"Error: $error")
  }
}
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.