Proposal for the Option/Maybe datatype

I would argue this case is that rare. In Kotlin we are very strict about nullability, null is not just a default/missing value as in Java - it has to be set explicitly and often it has a very specific meaning. Whenever we see a String? variable in the code, we know it is nullable for some reason and its null value is equally important to other values it could contain.

The problem arises if we have some kind of a container for other values, especially parameterized one. Similarly as above, if we use Map<String, String?> then we explicitly say we need to store null values in it. Null values are important to us, they mean something - otherwise we would use Map<String, String> instead. Unfortunately, it is not that easy to distinguish whether some key is missing in the map or it maps to a null value.

I know Map isn’t a great example, because it is partially dependent on how maps were designed and implemented in Java. I don’t say we should change Map interface. Still, I think Optional/Maybe in stdlib would be beneficial when designing some data structures and APIs in Kotlin.

Examples of real use cases:

  • Parsers/Serializers for formats like JSON, XML, protobuf, etc. When parsing we very often need to distinguish {"foo": null} and {}. Same when generating the data. In fact, Apollo GraphQL client for Java/Kotlin implements Optional/Maybe as their Input class.
  • Reading user input, configuration options or some other kind of parameters if there are default values. We need to know whether user set some parameter explicitly to null value or we should use the default value.
  • Storing partial updates to data objects. For example, we fetched a database entity and we would like to track in-memory changes to it before pushing to db. Or user was presented with a data form and we need to know which fields have been modified.
  • Calculating and storing differences between two Kotlin objects of the same type - this is similar to above.

I implemented Optional/Maybe in one of my projects: OptionalValue.kt. I utilized inline class with special Absent object, so I believe it should be pretty efficient CPU/memory-wise, but I didn’t test it thoroughly yet.

1 Like