TExcelTAD
Home › Scala › Scala Either

Scala Either

Option tells you that something is missing, but not why. Either[L, R] carries a reason. A value is either Left(error) or Right(result) — by convention Right is right, the success case. Either is the standard way to return expected errors without throwing exceptions.

Left and Right

scala · try it yourself
def divide(a: Int, b: Int): Either[String, Int] =
  if b == 0 then Left("cannot divide by zero")
  else Right(a / b)

@main def run(): Unit =
  println(divide(10, 2))
  println(divide(1, 0))

  divide(9, 3) match
    case Right(value) => println(s"result: $value")
    case Left(error)  => println(s"error: $error")
Right(5)
Left(cannot divide by zero)
result: 3

The return type Either[String, Int] documents both outcomes: a String error or an Int result.

Transforming: map and flatMap

Either is right-biased: map, flatMap, filterOrElse and for comprehensions work on the Right value and pass a Left through untouched.

scala · try it yourself
def parseAge(s: String): Either[String, Int] =
  s.toIntOption.toRight(s"'$s' is not a number")

def checkAdult(age: Int): Either[String, Int] =
  if age >= 18 then Right(age) else Left(s"$age is under 18")

@main def run(): Unit =
  println(parseAge("42").map(_ + 1))
  println(parseAge("x").map(_ + 1))
  println(parseAge("30").flatMap(checkAdult))
  println(parseAge("12").flatMap(checkAdult))
  println(parseAge("12").left.map(_.toUpperCase))
Right(43)
Left('x' is not a number)
Right(30)
Left(12 is under 18)
Right(12)

toRight(error) turns an Option into an Either. To transform the error side, use .left.map.

Chaining validations with for

A for comprehension stops at the first Left — exactly what you want when later steps depend on earlier ones.

scala · try it yourself
case class Signup(username: String, email: String, age: Int)

def validName(n: String): Either[String, String] =
  if n.length >= 3 then Right(n) else Left("username too short")

def validEmail(e: String): Either[String, String] =
  if e.contains("@") then Right(e.toLowerCase) else Left("invalid email")

def validAge(a: String): Either[String, Int] =
  a.toIntOption.filter(_ >= 13).toRight("age must be a number >= 13")

def signup(n: String, e: String, a: String): Either[String, Signup] =
  for
    name  <- validName(n)
    email <- validEmail(e)
    age   <- validAge(a)
  yield Signup(name, email, age)

@main def run(): Unit =
  println(signup("maya", "Maya@Mail.com", "21"))
  println(signup("mo", "mo@mail.com", "21"))
  println(signup("maya", "maya.mail.com", "x"))
Right(Signup(maya,maya@mail.com,21))
Left(username too short)
Left(invalid email)

The third call has two problems, but only the first is reported. To collect all errors, validate each field separately and combine the results (see below).

Getting results out

Method Purpose
fold(err => …, ok => …) handle both sides, produce one value
getOrElse(default) the right value or a default
isRight / isLeft test which side it is
toOption Some(right) or None (drops the error)
swap turn Left into Right and vice versa
left.map(f) transform the error

Collecting all errors

scala · try it yourself
def check(field: String, ok: Boolean): Either[String, Unit] =
  if ok then Right(()) else Left(s"$field is invalid")

@main def run(): Unit =
  val results = List(
    check("name", "mo".length >= 3),
    check("email", "mo@mail".contains("@")),
    check("age", "x".toIntOption.isDefined)
  )
  val errors = results.collect { case Left(e) => e }
  val (lefts, rights) = results.partitionMap(identity)
  println(errors)
  println(s"${lefts.size} failed, ${rights.size} passed")
  val outcome = if errors.isEmpty then "valid" else errors.mkString("; ")
  println(outcome)
List(name is invalid, age is invalid)
2 failed, 1 passed
name is invalid; age is invalid

Typed errors with an enum

Strings are fine for small programs; in larger code, model errors as an enum so callers can match on them precisely.

scala · try it yourself
enum TransferError:
  case InsufficientFunds(missing: BigDecimal)
  case AccountLocked(id: String)
  case InvalidAmount

def transfer(balance: BigDecimal, amount: BigDecimal, locked: Boolean): Either[TransferError, BigDecimal] =
  if amount <= 0 then Left(TransferError.InvalidAmount)
  else if locked then Left(TransferError.AccountLocked("ACC-1"))
  else if amount > balance then Left(TransferError.InsufficientFunds(amount - balance))
  else Right(balance - amount)

@main def run(): Unit =
  val attempts = List((BigDecimal(100), BigDecimal(30), false), (BigDecimal(100), BigDecimal(130), false),
                      (BigDecimal(100), BigDecimal(-5), false), (BigDecimal(100), BigDecimal(10), true))
  for (bal, amt, locked) <- attempts do
    val text = transfer(bal, amt, locked).fold(
      {
        case TransferError.InsufficientFunds(m) => s"missing $m"
        case TransferError.AccountLocked(id)    => s"$id is locked"
        case TransferError.InvalidAmount        => "amount must be positive"
      },
      newBalance => s"ok, new balance $newBalance"
    )
    println(text)
ok, new balance 70
missing 30
amount must be positive
ACC-1 is locked

Tip: Use Option when "missing" needs no explanation, Either when the caller needs to know what went wrong, and exceptions only for truly unexpected failures.

Test yourself

By convention, which side of an Either holds the successful result?

  1. Left
  2. Right
  3. Both
  4. Neither, it uses Some

What does Left("err").map((x: Int) => x + 1) return?

  1. Left(err)
  2. Right(1)
  3. It throws
  4. None

How do you convert Option[Int] into Either[String, Int]?

  1. opt.toEither
  2. opt.toRight("missing")
  3. Either(opt)
  4. opt.left