Java API design (for Kotlin consumption) ... Optional or null?

An advantage Optional/Maybe has over nullable types is that you can compose it. For example, you can have an Optional<Optional<Foo>>, but you can’t have a Foo??.

This is especially an issue with generic types where you want to be able to make a value of a type parameter optional. For example, suppose you have a type parameter T, and you try to use T? somewhere. If the user makes T a nullable type Foo?, now your T? is the same type as T.

This was an issue in Kotlin-Argparser, as I want the user to be able to specify any type for parsed arguments, including a nullable type, but I need to be able to distinguish between “the value is null” and “the value was never set”.

I didn’t actually use java.util.Optional, as I was trying to avoid the JDK 8 dependency. I ended up rolling a minimal Optional-like type in Kotlin. (Mine actually uses null for the empty case, but non-empty is in a property, which may be nullable.)

1 Like