🎓 A1Learner
🔍
0 of 50 lessons completed

Scala Option

An Option is a box that holds one value or is empty. Code can check the box before using the value, instead of failing when no value is there.

Some holds a value and None is empty

The two Option values print in different ways. One shows its value, and the other shows it is empty.

@main def main(): Unit =
  val found = Some(42)
  val missing = None
  println(found)
  println(missing)

Map.get returns an Option

The key apple is in the map, so its lookup gives Some(3). The key plum is missing, so getOrElse falls back to 0.

@main def main(): Unit =
  val prices = Map("apple" -> 3, "pear" -> 4)
  println(prices.get("apple"))
  println(prices.get("plum"))
  println(prices.get("plum").getOrElse(0))

Match reads the value inside

The Option holds 10, so the Some case fits. The name v holds the value from inside the box.

@main def main(): Unit =
  val result: Option[Int] = Some(10)
  result match
    case Some(v) => println(s"Got $v")
    case None => println("Nothing")

Example

def divide(a: Int, b: Int): Option[Int] =
  if b == 0 then None else Some(a / b)

@main def main(): Unit =
  println(divide(10, 2))
  println(divide(10, 0))
  println(divide(10, 0).getOrElse(-1))

Key points

  • Option: a box that either holds one value or holds nothing.
  • Some: an Option that holds a value, and it prints like Some(5).
  • None: an empty Option, and it prints as None.
  • Map.get: a lookup that returns an Option, giving Some for a found key and None for a missing key.
  • getOrElse: gives the value inside an Option, or a fallback value when the Option is None.
  • Option match: case Some(v) uses the value inside, and case None handles the empty box.

In this example, divide returns Some(a / b) when b is not zero, so divide(10, 2) prints Some(5). Dividing by zero returns None instead of failing, and getOrElse turns that None into the fallback -1.

Note

A def can return an Option to report that a result does not exist, without stopping the program.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Scastie

Exercise

What does Map.get return when the key is not in the map?