Scala Language Error Handling Option


The use of null values is strongly discouraged, unless interacting with legacy Java code that expects null. Instead, Option should be used when the result of a function might either be something (Some) or nothing (None).

A try-catch block is more appropriate for error-handling, but if the function might legitimately return nothing, Option is appropriate to use, and simple.

An Option[T] can either be Some(value) (contains a value of type T) or None:

def findPerson(name: String): Option[Person]

If no person is found, None can be returned. Otherwise, an object of type Some containing a Person object is returned. What follows are ways to handle an object of type Option.

Pattern Matching

findPerson(personName) match {
    case Some(person) => println(person.surname)
    case None => println(s"No person found with name $personName")

Using map and getOrElse

val name = findPerson(personName).map(_.firstName).getOrElse("Unknown")
println(name) // Prints either the name of the found person or "Unknown"

Using fold

val name = findPerson(personName).fold("Unknown")(_.firstName)
// equivalent to the map getOrElse example above.

Converting to Java

If you need to convert an Option type to a null-able Java type for interoperability:

val s: Option[String] = Option("hello")
s.orNull           // "hello": String
s.getOrElse(null)  // "hello": String

val n: Option[Int] = Option(42)
n.orNull           // compilation failure (Cannot prove that Null <:< Int.)
n.getOrElse(null)  // 42