Learning Kotlin: The notnull delegate and lateinit

Submitted by Robert MacLean on Mon, 09/03/2018 - 09:00
**More Information** * This is the 30th post in a multipart series. If you want to read more, see our [series index](/learning-kotlin-introduction) * This follows the [introduction to the `by` operator and delegates](/learning-kotlin-by-delegate-properties)

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 do not know what we want the value to be when we initialise the value and we know that when we use it we don't want to worry about nulls. The ability to change from null to never null might seem to be impossible but Kotlin has two ways to do the impossible.

Before we look at the two solutions, let us look at 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 here is there is no good default value. A house with just a ground floor is 0, a multistory office building could have 10 floors, and an underground bunker could have -30 floors.

  1. class Building() {
  2.     var numberOfFloors : Int
  3.  
  4.     fun getBuildingInfo(erfNumber : String){
  5.         // call municpality web service to get details
  6.         numberOfFloors = 0; // 0 cause 0 = G like in elevators
  7.     }
  8. }
  9.  
  10. fun main(args:Array<String>) {
  11.     val house = Building()
  12.     house.getBuildingInfo("123")
  13.     println("My house, up the road, has ${house.numberOfFloors}")
  14. }

This will not compile as it states Property must be initialized or be abstract for the number of floors.

notnull

Following on from our previous delegates we have the notnull delegate we can use to allow the property to not be set initially and then

  1. import kotlin.properties.Delegates
  2.  
  3. class Building() {
  4.     var numberOfFloors : Int by Delegates.notNull()
  5.  
  6.     fun getBuildingInfo(erfNumber : String){
  7.         // call municpality web service to get details
  8.         this.numberOfFloors = 10;
  9.     }
  10. }
  11.  
  12. fun main(args:Array<String>) {
  13.     val house = Building()
  14.     house.getBuildingInfo("123")
  15.     println("My house, down the street, has ${house.numberOfFloors}")
  16. }

This example will print out that we have 10 floors. If we were to comment out line 14, we would 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 makes no difference.

lateinit

Another option is lateinit which we can add before the var keyword, but we cannot use it with Int, or other primative types so we need to change that as well to a class. This is a really nice and simple solution.

  1. data class Floors(val aboveGround: Int, val belowGround: Int)
  2.  
  3. class Building() {
  4.     lateinit var numberOfFloors : Floors
  5.  
  6.     fun getBuildingInfo(erfNumber : String){
  7.         // call municpality web service to get details
  8.         this.numberOfFloors = Floors(2, 40);
  9.     }
  10. }
  11.  
  12. fun main(args:Array<String>) {
  13.     val house = Building()
  14.     house.getBuildingInfo("123")
  15.     println("My house, in the middle of the avenue, has ${house.numberOfFloors}")
  16. }

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 both have their own limitations and advantages too:

  • notnull being a delegate needs an extra object instance for each property, so there is a small additional memory/performance load.
  • The notnull delegate hides the getting and setting in a separate instance which means anything that works with the field, for example Java DI tools, will not work with it.
  • lateinit doesn't work with primitive types (Int, Char, Boolean etc...) as we saw above.
  • lateinit only works with var and not val.
  • when using lateinit you gain access to the.isInitialized method which you can use to check if it was initialized.