There are some classes whose object initialization is so time-consuming that it causes the entire class creation process to be delayed. Lazy initialisation helps in such problems. When we declare an object using lazy initialisation, the object is initialised only once when the object is used. If the object is not used throughout, the object is not initialised. This makes the code more efficient and faster.
For example, let us imagine you have a SlowClass class and you require an object of that SlowClass in a different class called FastClass:
// KOTLIN
class FastClass {
private val slowObject: SlowClass = SlowClass()
}
We are generating a large object here, which will cause the development of the FastClass to be slow or delayed. There may be times where the SlowClass object isn\\\'t required. As a result, the lazy keyword can assist you in this situation:
class FastClass {
private val slowObject: SlowClass by lazy {
SlowClass()
}
}
For example,
// KOTLIN
class FastClass {
private val slowObject: SlowClass by lazy {
println("Slow Object initialised")
SlowClass()
}
fun access() {
println(slowObject)
}
}
fun main(args: Array) {
val fastClass = FastClass()
println("FastClass initialised")
fastClass.access()
fastClass.access()
}
Output:-
FastClass initialised
Slow Object initialised
SlowClass@2b12fkk7
SlowClass@2b12fkk7
Explanation:- In the above code, we have instantiated an object of the SlowClass inside the class structure of the FastClass using lazy initialisation. The object of the SlowClass is generated only when it is accessed in the above code, that is, when we call the access() method of the FastClass object and the same object is present throughout the main() method.