Bang Bang: Drumming the nulls from your code

Handling null when converting from Java to Kotlin

Person playing on drums by Isaiah Colson is licensed under CC0

JetBrains gives us this great feature to convert our existing Java code into Kotlin. When you do this, you often find your files littered with !!s. These double bang operators are weak points where your app can crash. If you apply !! to a null object then Kotlin will throw a NullPointerException. No one really wants their app to fail in the hands of a user, so let’s get rid of !! from the converted code.

val drum = band.getDrum("timpani")
val beat = drum!!.bang() // Might throw an error

You have a number of options when it comes to handling null. Aside from leaving the double bang there, the option that requires the least amount of thinking is throwing the safe call operator at it. By doing so, you’re basically saying you want to ignore any dependent code if the value is null, and return null if you’re paying attention to the return value.

val drum = band.getDrum("timpani")
val beat = drum?.bang() // `beat` might be null

You can also give an optional value if the object is null. The Elvis operator lets you do this with ease. If there’s something you can substitute when the value is missing, this might be the way to go.

val drum = band.getDrum("timpani") ?: Drum("timpani")
val beat = drum.bang()

We should address the “do nothing” option. If it really is an error that the value is null, then you should raise it. But you can do better than the generic null error you would get. You should say why that is. David Vávra explains how you can be more descriptive in your error messages in part 6 of this post. By adding this description, you can more quickly identify what went wrong when the code throws an error.

val drum = requireNotNull(band.getDrum("timpani")) {
    "The band is missing the timpani"
val beat = drum.bang()

One more tip. Do your best to keep null out of your own code. Never return null yourself. Yes, you will be working with libraries and frameworks that have the potential to return null, but stop it at that seam. Handle the null value when you get it from the external source, and don’t let it propagate through your code. By keeping it isolated, there are much fewer places where you have to worry about null behavior, and your code will be cleaner with less null handling.

However you decide to handle nulls, make sure you’re intentional about it. Think about what the expected behavior is if the value is null. Should it stop what it’s doing? Is there a default value to use? Should it blow up? How does the decision affect what the end user will see? Take a moment to think when you come across a double bang.

Photo of Victoria Gonda

Victoria is a software developer working on mobile and full stack web applications. She enjoys exchanging knowledge through conference talks and writing.