Scala Language The Option type


Example

A nice example of a parameterized type is the Option type. It is essentially just the following definition (with several more methods defined on the type):

sealed abstract class Option[+A] {
  def isEmpty: Boolean
  def get: A

  final def fold[B](ifEmpty: => B)(f: A => B): B =
    if (isEmpty) ifEmpty else f(this.get)

  // lots of methods...
}

case class Some[A](value: A) extends Option[A] {
  def isEmpty = false
  def get = value
}

case object None extends Option[Nothing] {
  def isEmpty = true
  def get = throw new NoSuchElementException("None.get")
}

We can also see that this has a parameterized method, fold, which returns something of type B.