Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 37 ยท Functional Programming

Option, Either and Try in Scala

Handle missing values and errors without null or exceptions in Scala: Option, Some, None, Either, Left, Right and Try with map, flatMap, fold and recover.

Tony Hoare called the null reference his "billion dollar mistake". Scala code rarely uses null. Instead, it puts the possibility of absence or failure into the type, so the compiler reminds you to deal with it. Three types do most of the work:

  • Option[A]: a value that may be missing.
  • Either[E, A]: a result that is either an error E or a success A.
  • Try[A]: a computation that may have thrown an exception.

All three are small ADTs (see Enums and Sealed ADTs) and all three support map, flatMap, filter and pattern matching in the same way, which is why they combine so well.

Which one to use

Option Maybe there is a value. Some(x) or None.
Either Success or a described error. Right(x) or Left(e).
Try Wrap code that throws. Success(x) or Failure(ex).
1 / 2

Option

Some(value) holds a value; None is the absence of one.

SCALA
val users = Map(1 -> "Ann", 2 -> "Bo")

val a: Option[String] = users.get(1)   // Some(Ann)
val b: Option[String] = users.get(9)   // None

Many standard methods return an Option instead of null or an exception: Map.get, List.headOption, String.toIntOption, list.find(...).

Ways to use an option:

SCALA
// 1. Pattern matching
a match
  case Some(name) => println(s"Hi $name")
  case None => println("nobody")

// 2. map, filter and flatMap
val upper = a.map(_.toUpperCase)              // Some(ANN)
val longName = a.filter(_.length > 5)         // None
val firstChar = a.flatMap(_.headOption)       // Some(A)

// 3. Defaults
val name1 = b.getOrElse("guest")              // guest
val name2 = b.orElse(users.get(2))            // Some(Bo)

// 4. fold: one expression for both cases
val label = a.fold("no user")(n => s"user: $n")   // user: Ann

Avoid option.get: it throws NoSuchElementException on None, which is exactly the failure Option was meant to prevent.

flatMap is the key operation for chaining steps that might each yield nothing:

SCALA
case class User(id: Int, managerId: Option[Int])
val db = Map(1 -> User(1, Some(2)), 2 -> User(2, None))

def managerOf(id: Int): Option[User] =
  db.get(id).flatMap(_.managerId).flatMap(db.get)

println(managerOf(1))   // Some(User(2,None))
println(managerOf(2))   // None
println(managerOf(7))   // None

If any step is None, the rest are skipped, and there are no nested if (x != null) checks. You will see the nicer syntax for this chain in For-Comprehensions.

Wrap values from Java code with Option(x): Option(null) is None while Some(null) is a bug waiting to happen.

Either

Option says that something is missing but not why. Either[E, A] carries a reason. By convention Right is the success ("right" is also "correct") and Left is the error.

SCALA
def parseAge(s: String): Either[String, Int] =
  s.toIntOption match
    case None => Left(s"'$s' is not a number")
    case Some(n) if n < 0 => Left("age cannot be negative")
    case Some(n) => Right(n)

println(parseAge("42"))    // Right(42)
println(parseAge("abc"))   // Left('abc' is not a number)
println(parseAge("-3"))    // Left(age cannot be negative)

Since Scala 2.12 Either is right-biased: map and flatMap work on the Right and pass a Left through untouched.

SCALA
case class Person(name: String, age: Int)

def validateName(s: String): Either[String, String] =
  if s.trim.isEmpty then Left("name is empty") else Right(s.trim)

def makePerson(name: String, age: String): Either[String, Person] =
  validateName(name).flatMap(n => parseAge(age).map(a => Person(n, a)))

println(makePerson("Ann", "30"))   // Right(Person(Ann,30))
println(makePerson("", "30"))      // Left(name is empty)
println(makePerson("Ann", "x"))    // Left('x' is not a number)

It stops at the first error. If you want all errors at once you need a validation type from a library such as Cats, but Either is perfect for fail-fast code. Use an ADT for the error side to make failures precise:

SCALA
enum AppError:
  case NotFound(id: Int)
  case Invalid(reason: String)

Useful methods: fold(onLeft)(onRight), getOrElse, left.map, toOption, swap and Either.cond(test, right, left).

Try

Try[A] wraps code that might throw. Success(value) holds the result; Failure(exception) holds the exception, so nothing escapes:

SCALA
import scala.util.{Try, Success, Failure}

val ok = Try("42".toInt)            // Success(42)
val bad = Try("x".toInt)            // Failure(java.lang.NumberFormatException: For input string: "x")

ok.map(_ + 1)                       // Success(43)
bad.map(_ + 1)                      // Failure(...), unchanged
bad.getOrElse(0)                    // 0
bad.recover { case _: NumberFormatException => -1 }   // Success(-1)

bad match
  case Success(n) => println(n)
  case Failure(e) => println(s"failed: ${e.getMessage}")

Try only catches non-fatal exceptions: it does not catch OutOfMemoryError or InterruptedException. It is the right tool to wrap Java methods that throw (Try(Integer.parseInt(s)), Try(Files.readString(path))) and convert them into values. Do not use it for your own business errors; there Either with a proper error type is clearer.

Convert between them as needed: try.toOption, try.toEither, option.toRight(errorValue) and either.toOption.

flowchart LR
    T["Try[A]"] -->|toEither| E["Either[Throwable, A]"]
    T -->|toOption| O["Option[A]"]
    E -->|toOption| O
    O -->|toRight err| E

The same pattern in Java and Kotlin

The next two examples are Java and Kotlin, not Scala. Java's Optional and Kotlin's nullable types and runCatching solve the same problem.

Java Java: Optional map, flatMap, orElse (Java, not Scala)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Kotlin Kotlin: Result and runCatching (Kotlin, not Scala)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Common mistakes

  • Calling .get on Option or Try. Use getOrElse, fold or pattern matching.
  • Some(null). Use Option(x) for values from Java.
  • Using Try for business validation. Reach for Either with a meaningful error type.
  • Swallowing errors with .getOrElse(default) where the user should be told what went wrong.
  • Returning Option[Option[A]] by using map where flatMap was needed.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does Option(null) evaluate to?

    Option.apply turns null into None, which makes it the safe way to wrap values from Java.
  2. 2. Given Left("oops").map(_ + 1) on an Either[String, Int], what is the result?

    Either is right-biased: map and flatMap operate on the Right value and pass a Left through.
  3. 3. When is Try the best choice?

    Try captures non-fatal exceptions as Failure values. For expected business errors, Either with a custom error type is clearer.
  4. 4. What does users.get(9).getOrElse("guest") return if the map has no key 9?

    get returns None for a missing key and getOrElse supplies the default.

Summary

  • Option models absence, Either models success-or-error with a reason, Try captures exceptions.
  • All three support map, flatMap, filter, fold and pattern matching; failures propagate automatically through chains.
  • Avoid null and .get; use Option(x) at Java boundaries.
  • Use an ADT as the Left type for precise, matchable errors, and convert between types with toOption, toEither and toRight.

Next: For-Comprehensions