Using Either to process failures in Scala code

Either is used to return one of possible two meaningful results, unlike Option which is used to return a single meaningful result or nothing.

An easy to understand example is given below (circulated on the Scala mailing list a while back):

def throwableToLeft[T](block: => T): Either[java.lang.Throwable, T] =
  try {
    Right(block)
  } catch {
    case ex => Left(ex)
  }

As the function name implies, if the execution of “block” is successful, it will return “Right(<result>)”. Otherwise, if a Throwable is thrown, it will return “Left(<throwable>)”. Use pattern matching to process the result:

var s = "hello"
throwableToLeft { s.toUpperCase } match {
  case Right(s) => println(s)
  case Left(e) => e.printStackTrace
}
// prints "HELLO"

s = null
throwableToLeft { s.toUpperCase } match {
  case Right(s) => println(s)
  case Left(e) => e.printStackTrace
}
// prints NullPointerException stack trace

Hope that helps.

Leave a Comment