Why null handling in Kotlin sucks.

10 Nov 2013

Null sucks. We all know this. We’ve all written code like this:

Person person = database.getSomePerson();
if (person != null) {
  Address address = person.getAddress();
  if (address != null) {
    City city = address.getCity();
    if (city != null) {
      return city.getPopulation();
    }
    return null
  }
  return null;
} 
return null;

The issue here is that when we fetch a person from the database, it could very possibly be null. We don’t know. And at each subsequent field request, they could also be null. So we’re forced to defensively check for null at each get, leading to extremely ugly code.

I want to talk about Kotlin however. The language comes with some interesting concepts around null. Any reference that CAN be null, have a different type. This allows null to be encoded IN the type system, not hanging around as an exception case (looking at you Java).

This allows code like the following: