Advantages of Option
types:
- No need to implement flow typing, which can be hard to get right
- Can be used with primitive types (
Int?
would require boxing in a language with nullable types, removing the performance benefits) - Can be nested - A function can accept an
Option<T>
, whereT
may itself beOption<Foo>
. With boxing, it's possible to distinguish between aSome(None)
and aNone
in this case. This isn't possible with nullable types (Int??
isn't a thing in Kotlin). - Can implement interfaces such as
Iterable
or typeclasses such asMonad
Advantages of nullable types:
- Syntactically lighter - It can be cumbersome to write
Option<T>
andSome(x)
everywhere, while in a language like Kotlin, you only need to writeT?
andx
. Note: alephalpha pointed out in the comments that this isn't always true - the syntax for Zig's optional types looks similar to that of nullable types in other languages. - With flow typing, once you check that a value is not null, you don't need to check again (in most circumstances). That means you can do
if (x != null) x.foo(x.bar)
rather thanif (x.nonEmpty) x.get.foo(x.get.bar)
orx.map(y => y.foo(y.bar))
- No boxing means that they take up less space and there's a performance benefit since you don't need to unwrap a
Some
/Just
every time you want to access the value inside. As Bbrk24 mentioned in the comments, though, languages such as Rust and Swift can implement Options without boxing or with only a single bit to indicate whether the Option is empty, so this point only applies to certain languages. For example, Scala boxes itsOption
s (although it's entirely possible to have nestable unboxed Options even in a language that doesn't natively support them, depending on your language's type system).