Late-Initialized Properties in Kotlin

There can be two ways to declare and initialize a var property

var variable : CustomClass = CustomClass() 
or
var variable : CustomClass? = null

The first property is initialized while declaration itself and doesn’t require a null check (?.) while using it.

This post was originally posted at https://agrawalsuneet.github.io/blogs/lateinit-property-in-kotlin/ and reposted on Medium on 10th Nov 2017.

But in the second type, the property is initialized with a null value and will require a null check (?.) always while using it.

variable?.someMethodCall()//orvariable!!.someMethodCall()

There can be a use case where we don’t want to initialize the property while declaration but also at the same time we don’t want a null check on that property every time as we are sure that while using that property, it’s value will be not null for sure. Conditions like initialization of property via dependency injection or in a setup method of unit test.

To handle this kind of cases, we can mark the property with the ‘lateinit’ modifier

lateinit var variable : CustomClass

the property ‘variable’ can be initialized later in the constructor or in any method before accessing it. Also, it doesn’t require a null check (!!) every time while using it.

variable = CustomClass()
variable.someMethodCall()

Limitations of Late-Initialized Properties

  1. lateinit can only be used with var properties declared inside the body of class (not in the primary constructor) but not inside any method.
  2. It can only be used when the property does not have a custom getter or setter.
  3. The type of the property must be non-null, and it must not be a primitive type.
  4. Accessing a lateinit property before it has been initialized throws a special exception that clearly identifies the property being accessed and the fact that it hasn’t been initialized.

That’s all for now. You can read my other interesting posts here or you can enjoy my games or apps listed here. Feel free to use my open-source Android components in your app listed here. Or drop an email, if you didn’t find what you are looking for and need some help.