The Option
structure is a list that contains 0 or 1 element (
sound familiar?) — and is not recursive like List
.
sealed trait Option[+A] final case object None extends Option[Nothing] final case class Some[+A](a: A) extends Option[A]
Option
is a better null
than null
.
Consider a Map.get(K)
that returns an Option[V]
— not just a V
.
The flatMap
method is one example of a method written over the Option
algebraic
type.
X x = method1(args1); if(x == null) return null; else { Y y = method2(x, args2); if(y == null) return null; else return method3(y, args3);
Ick!
method1(args1) flatMap (method2(_, args2)) flatMap (method3(_, args3))