July 25, 2020
The Null Pointer Problem
Java devs have struggled withe the Problem of the NullPointerException for years and more years to come. It has been named the ‘Billion Dollar Mistake’ and it probably did cost something ranging in this number.
Kotlin is coming up with a pretty neat solutions to this old Problem. It does not prevent NullPonterExceptions completely but it warns you every time you are about to introduce code that could lend to this technical debt.
If you declare a standard variable in Kotlin and initialize it with null:
val text:String = null
The Kotlin compiler wont let you do that and will throw an Exception:
Null can not be a value of a non-null type String
To mark the variable as nullable and allow to initialize it with null you can add a
? to the type of the variable.
val text:String? = null
This has the effect, that you can’t use this variable in following operations without checking for null each time. It works similar to Javas
The advantage compared to Javas annotations is clear. This Nullable-Mark is present without adding an extra annotation and though possibly forget to add it.
To access nullable variables Kotlin has two methods available.
First option is to return
null if the variable is nullable.
val text:String? = null println(text?.length)
null on the standard output.
If that isn’t suitable you can choose the
!! operator which throws a NullPointerException (NPE) if the variable is null.
val text:String? = null println(text!!.length)
Would result in a NPE being thrown.
A third option would be, to use the so called Elvis operator
val text:String? = null println(text?.length :? 0)
This operator allows to return another value in case the variable is
null this statement prints out
Sometimes you are in the situation that you need to declare a variable ahead of the time you use it.
But you know that this variable will never be null when you actually use it.
To implement this you can use the
lateinit variable modifier.
lateinit var text:String text = "test" println(text.length)
This code compiles without any error. If you omit the variable assignment you would get a
For further information see the documentation to nullability in the official kotlin documentation: Null Safety