Optionals
Throughout the previous sections, we have discussed Kotlin's approach to null safety. But this is not the only approach. Languages such as Haskell have provided an alternative for many years. In Haskell's case, this is called the Maybe
type. In Scala there is something similar called the Option
type, and in the most recent version of Java (at the time of writing, Java 8) there is Optional
.
All of these types-Maybe
, Option
, Optional
-aim to do the same thing. That is, they use a type to indicate that a function or expression may or may not return a value.
In Functional programming. they are most often an algebraic data type with two values-one that represents a value and one that represents the lack of a value. In Haskell they are called Just
and Nothing
. In Scala they are called Some
and None
. In Java only a single type is used.
For the rest of this section, we will focus on the Java Optional. Remember, though, that this will not be available to you if you are not compiling on Java...