Option[A] makes a possibly absent result explicit in a function’s return type. Some(a) represents a defined value; None represents no value. A mean for an empty sequence can therefore return None rather than a sentinel value or an exception, while remaining total: every input produces an Option[Double]. The caller, not a hidden control-flow path, chooses how to respond to absence. section 4.3 section 4.6
Listing 4.2 The Option data type
enum Option[+A]: case Some(get: A) case None def map[B](f: A => B): Option[B] #1 def flatMap[B](f: A => Option[B]): Option[B] #2 def getOrElse[B >: A](default: => B): B #3 def orElse[B >: A](ob: => Option[B]): Option[B] #4 def filter(f: A => Boolean): Option[A] #5
The core operations preserve the optional context: map transforms a present value, flatMap continues a computation that may also be absent, getOrElse supplies a fallback, orElse chooses an alternative Option, and filter can turn a value into None. section 4.3.1
Treat Option like a collection with at most one element. map avoids manual matching when a transformation cannot fail; flatMap avoids nesting when the next step also returns Option. This lets a lookup flow through a field selection, or lets mean feed a second computation for variance, without separately handling Some and None at each call. section 4.3.1 section 4.6
Combine independent optional inputs
Parsing an insurance form produces an Option[Int] for age and another for speeding tickets. map2 combines them with insuranceRateQuote only when both are present; otherwise the result is None. The same pattern scales to sequence, which turns a List[Option[A]] into an Option[List[A]], and traverse, which applies an Option-producing function across a list. section 4.3.2 section 4.6
Option does not require rewriting ordinary functions. lift converts an A => B function into Option[A] => Option[B] by using map, so math.abs can operate on an optional number. Exception-oriented APIs can be wrapped at the boundary—for example, converting a failed String-to-Int parse into None—then composed as ordinary values thereafter. section 4.3.2
When optional computations are independent, map2 combines their results with a fixed computation structure. When a later lookup depends on an earlier result, flatMap selects that next lookup. This distinction connects Option to Applicative and Monad while retaining the same possibility-of-failure context. section 12.3.1
Option records only that a result is absent, not why. Use it for expected missing or undefined results; richer error information calls for Either, while exceptions remain for truly unrecoverable conditions. section 4.6 section 4.5








