From Java to Kotlin – Part VII: Null Safety
Considering a move to Kotlin? Coming from a Java background? In this short series of blog posts, I’ll take a look at familiar, straightforward Java concepts and demonstrate how you can approach them in Kotlin. While many of these points have already been discussed in earlier posts by colleagues, my focus is simple: how you used to do it in Java, and how you do it in Kotlin.
Case 7: Nulls exist.
Ignoring them doesn’t make them go away.
The problem
NullPointerExceptions are still the most popular Java exception. For all the wrong reasons.
Okay, the NullPointerExceptions aren’t really the problem — They’re the symptom. And Java makes it very easy to create that symptom.
In Java, any reference can be null unless you actively prevent it. Fields, method parameters, return values, collections… all fair game.
Example:
String city = user.getAddress().getCity().toUpperCase();
As you can see, this can explode at three different points, and the compiler is totally fine with it.
-
user.getAddress()whenuseris null -
user.getAddress().getCity()whenuser.getAddress()is null -
the return value of
getCity()when you immediately dereference it (getCity().toUpperCase())
The Kotlin way
val name: String? = null
println(name?.length ?: "Unknown")
Nullability is explicit. Handled by the compiler.
Why this matters
You see nulls before runtime. Not after deployment.
Takeaway
Kotlin turns runtime bugs into compile-time decisions. That’s a trade worth making.