The Scala Option
type is an algebraic data type (ADT) that represents an optional value. It can also be viewed as List
that can contain either one or no elements. It is a safe replacement for a null
reference that you might have used if you have programmed in Java, C++, or C#.
The following is a simplified definition of the Option
ADT:
sealed trait Option[+A] case class Some[A](value: A) extends Option[A] case object None extends Option[Nothing]
The Scala SDK provides a more refined implementation; the preceding definition is just for illustrative purpose. This definition implies that Option
can be either of the following two types:
Some(value)
, which represents an optional value where the value is presentNone
, which represents an optional value where the value is not present.
Note
The +
sign in front of the A
type parameter in the Option[+A]
declaration means that Option
is covariant in A
. We will explore contravariance in more details in Chapter...