Blog / November 10, 2017 / 2 mins read / By Suneet Agrawal

lateinit Property 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.

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()
//or
variable!!.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).
  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.
Comments