Cleanup your Kotlin: Handling nullable reference

Kotlin programming language provides developers with expressive distinction of nullable types. Nevertheless, dealing with nullability can easily become awkward. Of course we don’t need to polute our code with unnecessary null checks, question marks or exclamation marks. Let’s see how to improve our codebase with a very little effort.

Image for post
Image for post

Introduction

Don’t trust your IDE (that much)

IntelliJ IDEA — implement members action result
Remove nullability in Java interface arguments when it makes sense. Quite common case, not 100% safe though.

Adjust your data model

Suspicious data class
Introducing new data type when appropriate may reduce the need for nullable types.

Filter the null values out

filterNotNull kotlin function example
mapNotNull kotlin function example
listOfNotNull kotlin function example

Safe call — lambda combination

Elvis to the rescue

Keep the null in scope it appeared

Summary

Written by

Software developer in Quadient. Experienced in Kotlin, Typescript, and stuff.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store