Lateinit is an important initialization property, because if you don't want to initialize your variable in constructor, lazy
and lateinit
can be employed to do so. In this recipe, we will see how to use the lateinit
modifier and how it is different from the lazy
modifier.
I'll be using IntelliJ IDEA for the coding purpose; you can use any IDE that can execute Kotlin code.
Let's follow the given steps to understand how the lateinit
modifier works:
- In Java, we could just declare a variable beforehand and initialize it later, but Kotlin requires you to initialize it as soon as you declare it (unless you are using special modifiers). So you can do the following:
var student:Student?=null
Alternatively, you can do this:
val student=Student()
Both ways have their drawbacks. The first way will require you to check nullability whenever you use it, and the second way of initializing will make it immutable.
- To overcome limitations, we can use a
lateinit...