Learning Kotlin
Kotlin variable, to be Lazy, or to be Late?
Decide which is better to use in which circumstances
In Kotlin, we are now introduced to two new features of an old concept, lazy initialization i.e. the deferring of a variable initialization to a later time. This is a very handy feature, as we don’t need to initialize something that until we need it, or simply because we can’t initialize something until we have all we need.
Let me first introduce the two syntactically
Initialization by Lazy
val myUtil by lazy {
MyUtil(parameter1, parameter2)
}
The above code is initializing a MyUtil object. But this will only be done upon the first usage of myUtil.
Late Initialization
lateinit var myUtil: MyUtil
and somewhere in one of the function
myUtil = MyUtil(parameter1, parameter2)
The code basically differs the initialization until when it is initialized.
Why two? Use cases?
Though both have the same concept but are actually very different in nature. Simply looking at the variable type, one is val (immutable) and the…