A partial function is defined for only some inputs. Its input type permits values for which the function has no meaningful result, as with mean on an empty sequence. section 4.2
Mean of an empty sequence
A naive mean implementation can throw an exception when xs.isEmpty, return Double.NaN, or use another sentinel. These choices let errors propagate silently, burden callers with checks, and fail for polymorphic results where no sentinel exists. Returning Option makes the missing case explicit: mean(xs) yields None for an empty sequence and Some(value) otherwise. section 4.2 section 4.3.1
Option turns partiality into data that callers must handle deliberately. Its map, flatMap, filter, getOrElse, and orElse operations factor out repeated error-handling control flow and allow computations to be chained without exceptions. section 4.3.1
Common partial operations represented with Option include:
- Looking up a key in a map returns an optional value. section 4.3.1
- Retrieving the first or last element of a possibly empty sequence returns an Option. section 4.3.1
- Chaining lookup, transformation, filtering, and a default can produce a usable result without explicit exception handling. section 4.3.1
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
Inspect the core Option operations used to represent and compose partial results. section 4.3.1
