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

The Either Type

An Either holds one of two possible answers, usually a bad one on the left or a good one on the right. It is like a door that opens to either a prize or an explanation.

In this page:

  1. The Either Type
Syntax
scala
def function_name(param: Type): Either[ErrorType, ResultType] =
  if (condition) Right(value) else Left(error)

result match {
  case Left(error) => expression
  case Right(value) => expression
}

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")
  }
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Assuming Left is the success value, when by convention Right is the correct value and Left is the error.
  2. Forgetting the types, such as Either[String, Int], so the compiler infers Either[String, Nothing].
  3. Calling .get on an Either, when it has no get and you should use match, map or fold.
🔒

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.