TExcelTAD
Home › Scala › Scala Option

Scala Option

Tony Hoare, who invented the null reference, later called it his "billion-dollar mistake". Scala code avoids null by using Option[A]: a value that is either Some(value) or None. The type itself tells every reader — and the compiler — that the value might be missing, so you cannot forget to handle that case.

Some and None

scala · try it yourself
def findPhone(name: String): Option[String] =
  val book = Map("ana" -> "555-0101", "raj" -> "555-0199")
  book.get(name)

@main def run(): Unit =
  println(findPhone("ana"))
  println(findPhone("zoe"))
  println(findPhone("ana").isDefined)
  println(findPhone("zoe").isEmpty)
Some(555-0101)
None
true
true

Many library methods already return options: Map.get, headOption, find, lastOption, toIntOption, maxOption and more.

Getting the value out safely

Method Result for Some(5) Result for None
getOrElse(0) 5 0
orElse(Some(9)) Some(5) Some(9)
fold("none")(_.toString) "5" "none"
contains(5) true false
get 5 throws — avoid
scala · try it yourself
@main def run(): Unit =
  val present: Option[Int] = Some(5)
  val missing: Option[Int] = None
  println(present.getOrElse(0))
  println(missing.getOrElse(0))
  println(missing.orElse(Some(9)))
  println(present.fold("none")(n => s"got $n"))
  println(missing.fold("none")(n => s"got $n"))

  val message = present match
    case Some(n) if n > 3 => s"big: $n"
    case Some(n)          => s"small: $n"
    case None             => "nothing"
  println(message)
5
0
Some(9)
got 5
none
big: 5

Transforming with map, filter and flatMap

You rarely need to unpack an option. Treat it like a collection with zero or one element and transform it directly. None simply flows through.

scala · try it yourself
case class User(name: String, managerId: Option[Int])

val users = Map(
  1 -> User("Ada", None),
  2 -> User("Ben", Some(1)),
  3 -> User("Cleo", Some(7))   // manager 7 does not exist
)

def managerName(id: Int): Option[String] =
  users.get(id).flatMap(_.managerId).flatMap(users.get).map(_.name)

@main def run(): Unit =
  println(managerName(2))
  println(managerName(1))
  println(managerName(3))
  println(managerName(99))
  println(Some(" hi ").map(_.trim).filter(_.nonEmpty))
  println(Some("   ").map(_.trim).filter(_.nonEmpty))
Some(Ada)
None
None
None
Some(hi)
None

map transforms the value if present; flatMap is used when the transformation itself returns an Option, so you don't end up with Some(Some(…)).

for-comprehensions with Option

When several optional values must all be present, a for expression reads much more naturally than nested flatMap calls. If any step is None, the whole result is None.

scala · try it yourself
def parsePoint(x: String, y: String): Option[(Int, Int)] =
  for
    a <- x.toIntOption
    b <- y.toIntOption
    if a >= 0 && b >= 0
  yield (a, b)

@main def run(): Unit =
  println(parsePoint("3", "4"))
  println(parsePoint("3", "four"))
  println(parsePoint("-1", "4"))
Some((3,4))
None
None

Options in collections

flatten and flatMap drop the Nones and unwrap the Somes, which is perfect for "keep only the valid ones":

scala · try it yourself
@main def run(): Unit =
  val inputs = List("10", "abc", "25", "", "7")
  val numbers = inputs.flatMap(_.toIntOption)
  println(numbers)
  println(inputs.map(_.toIntOption).flatten.sum)
  println(List.empty[Int].maxOption)
  println(numbers.find(_ > 20))
  Option("log me").foreach(println)
List(10, 25, 7)
42
None
Some(25)
log me

Working with Java and null

Java libraries may return null. Wrap such values with Option(value), which turns null into None:

scala
val fromJava: String = System.getenv("SOME_UNSET_VARIABLE") // may be null
val safe: Option[String] = Option(fromJava)                  // None if null

Tip: Never call .get on an Option in production code. If you are sure a value exists, say so with getOrElse(throw ...) and a clear message, or restructure so the compiler can see it.

Test yourself

What does Some(4).map(_ * 2) return?

  1. 8
  2. Some(8)
  3. None
  4. Some(Some(8))

What does Option(null) evaluate to?

  1. Some(null)
  2. None
  3. It throws
  4. null

What is List(Some(1), None, Some(3)).flatten?

  1. List(1, 3)
  2. List(Some(1), Some(3))
  3. List(1, None, 3)
  4. 4