Ignoring Kotlin’s Null Safety

So hands up: whom among us has ever written code that threw a NullPointerException? And those with your hands down: you are either lying or have never written software! [And, yes, my hand is up, and for multiple languages.]

A major feature of Kotlin is its built-in null safety which explicitly declares the nullability (or lack thereof) for a class member, method return type, and local variable. This compile-time checking on usage and allows the compiler to find (most) nullness bugs rather than waiting for runtime failures. Your code quality should improve when used correctly.

Unfortunately, I often find production code which devolves to Java-like null handling, i.e. it’s up to the engineer to correctly deal with it.

Example 1

Take this trivial variable declaration:

var myList: List<SomeClass?>?

Two fundamental problems, in my opinion:

  • Null Elements In List: technically legal but often a code smell, useful for in-order comparisons of multiple lists but in fact rarely necessary.
  • Null List: the list itself is nullable, why not replace with an empty list?

Example 2

Queries against persistence repositories may be implicitly defined in Spring Data by declaring methods with names that are translated into whatever the corresponding query language is. The following method declaration queries a repository for all users with the specified email domain.

fun findByEmailDomain(emailDomain: String): List<User?>?

Again, two fundamental problems, both due to the engineer not understanding how Spring Data works:

  • Null Elements In List: Either the emailDomain matches that of a User and is added to the list returned or the emailDomain doesn’t match and User isn’t added; null elements are never in the returned list.
  • Null List: an empty list is returned when no matching Users are found, never a null.

[I’ve also seen nullable query parameters even when the persisted field/column/property is required.]

Conclusion

Though still possible to throw NullPointerException‘s in your Kotlin code, using its null-safety constructs greatly reduces the situations where they occur. It is time well spent when engineers look for opportunities to leverage Kotlin’s null-safety to eliminate manual null handling in their code.