Scala Option in Depth
An Option value in depth is a container that is either Some value or None and can be transformed without opening it. It keeps the missing case inside the value until the end.
Map transforms Some and leaves None alone
Doubling Some 5 gives Some 10. Doubling None still gives None.
@main def main(): Unit =
val a = Some(5)
println(a.map(_ * 2))
val b: Option[Int] = None
println(b.map(_ * 2))FlatMap chains steps that return Option
halfEven returns Some only for even numbers. 12 halves to 6, while 9 and None give None.
@main def main(): Unit =
def halfEven(x: Int): Option[Int] = if x % 2 == 0 then Some(x / 2) else None
println(Some(12).flatMap(halfEven))
println(Some(9).flatMap(halfEven))
val n: Option[Int] = None
println(n.flatMap(halfEven))Fold and orElse handle both cases
Fold doubles Some 8 to 16 and gives 0 for None. OrElse supplies Some 7 when the first value is None.
@main def main(): Unit =
println(Some(8).fold(0)(_ * 2))
val n: Option[Int] = None
println(n.fold(0)(_ * 2))
println(n.orElse(Some(7)))Example
@main def main(): Unit =
val scores = Map("Ana" -> 90, "Bo" -> 70)
println(scores.get("Ana").map(_ + 5))
println(scores.get("Zoe").map(_ + 5))
println(scores.get("Zoe").orElse(Some(0)))Key points
- Map on Option: transforms the value inside Some and leaves None unchanged.
- FlatMap on Option: chains a step that itself returns an Option, without nesting.
- Filter on Option: keeps Some only when its value passes a test, else gives None.
- Fold on Option: gives one result for both cases, with the empty value first.
- OrElse on Option: supplies a fallback Option when the first one is None.
In this example, a map lookup returns an Option for each name. Ana is found, so adding 5 gives Some 95. Zoe is missing, so mapping gives None, and orElse supplies Some 0 as the fallback.
Note
chaining on Option never throws for a missing value. The missing case travels through the chain.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Scastie
Exercise
What is Some(4).flatMap(x => Some(x * 3))?