Learning Kotlin: The notnull delegate and lateinit
Note This is the 30th post in a multipart series. If you want to read more, see our series index. This follows the introduction to the by operator and delegates.
A lot of introductions to Kotlin start with how null is opt-in because that makes it safer—we even looked at this way back in post 8. The problem, though, is that sometimes we don’t know what we want the value to be when we initialize it and we know that when we use it we don’t want to worry about nulls. The ability to change from null to non-null might seem impossible, but Kotlin has two ways to do the impossible. Before we look at the two solutions, let’s examine a non-working example.
Here we have a class to represent a physical building, and we want to store the number of floors, which we get from calling an API (not shown). The problem is there’s no good default value: a house with just a ground floor is 0, a multi-story office building could have 10 floors, and an underground bunker could have -30 floors.
class Building() {
var numberOfFloors: Int
fun getBuildingInfo(erfNumber: String) {
// call municipality web service to get details
numberOfFloors = 0; // 0 causes 0 = G like in elevators
}
}
fun main(args: Array<String>) {
val house = Building()
house.getBuildingInfo("123")
println("My house, up the road, has ${house.numberOfFloors}")
}
This won’t compile as it states: Property must be initialized or be abstract for the numberOfFloors field.
notnull
Following on from our previous delegates, we have the notNull delegate (import: kotlin.properties.Delegates) to allow the property to not be set initially and then enforce initialization later.
import kotlin.properties.Delegates
class Building() {
var numberOfFloors: Int by Delegates.notNull()
fun getBuildingInfo(erfNumber: String) {
// call municipality web service to get details
this.numberOfFloors = 10;
}
}
fun main(args: Array<String>) {
val house = Building()
house.getBuildingInfo("123")
println("My house, down the street, has ${house.numberOfFloors}")
}
This example will print that we have 10 floors. If we comment out line 14, we’d get the following exception:
Exception in thread "main" java.lang.IllegalStateException: Property numberOfFloors should be initialized before get.
So not exactly a null exception, but close enough—it achieves the same goal.
lateinit
Another option is lateinit, which we can add before the var keyword—but we can’t use it with primitive types like Int or other primitive types. Instead, we need to convert it to a class. This is a nice and simple solution.
data class Floors(val aboveGround: Int, val belowGround: Int)
class Building() {
lateinit var numberOfFloors: Floors
fun getBuildingInfo(erfNumber: String) {
// call municipality web service to get details
this.numberOfFloors = Floors(2, 40);
}
}
fun main(args: Array<String>) {
val house = Building()
house.getBuildingInfo("123")
println("My house, in the middle of the avenue, has ${house.numberOfFloors}")
}
Once again, if we comment out line 14, we get an exception as expected:
Exception in thread "main" kotlin.UninitializedPropertyAccessException: lateinit property numberOfFloors has not been initialized.
lateinit vs. notnull
As we can see in our simple examples, both achieve the goal—but they each have their own limitations and advantages:
notNullbeing a delegate requires an extra object instance for each property, so there’s a small additional memory/performance overhead.- The
notNulldelegate hides the getting and setting logic in a separate instance, which means anything that works with the field (e.g., Java DI tools) won’t work with it. lateinitdoesn’t work with primitive types (Int,Char,Boolean, etc.), as we saw above.lateinitonly works withvarand notval.- When using
lateinit, you gain access to the.isInitializedmethod, which you can use to check initialization status.