There can be two ways to declare and initialize a var property
var variable : CustomClass = CustomClass()
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.
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()
Limitations of Late-Initialized Properties
- lateinit can only be used with var properties declared inside the body of class (not in the primary constructor) but not inside any method.
- It can only be used when the property does not have a custom getter or setter.
- The type of the property must be non-null, and it must not be a primitive type.
- 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.