In programming languages (especially functional programming languages) an option type is a polymorphic type that represents encapsulation of an optional value; e.g. it is used as the return type of functions which may or may not return a meaningful value when they're applied. It consists of either an empty constructor (called None()), or a constructor encapsulating the original data type A (written Some A).
It allows to build up calculations based on values that can be valid or not, without having to test the value until the very end of the calculation. Most often Option avoids the use of nil checks, i.e. statements like if(x.notNil) { foo.bar(x) }.
This class is copied from the Scala Option class.
For more information see http://en.wikipedia.org/wiki/Option_type.
Is a type instance of Functor, Applicative Functor, Monad
nil checks can be converted to Option checks by doing myObject.asOption
. This will convert nil values to None() and all other values to Some. This is different from using pure, because nil.pure(Option)
will output a Some(nil)
not a None()
.
x |
Some(x)
None()
With arrays:
Dictionary.get returns None() if the key doesn't exist and Some(x) if they key has value x.
Access a 3 level dictionary hierarchy without ever using any if statement: