Lazy Initialization
For efficient memory management, Kotlin has introduced a new feature called Lazy initialization.
When the lazy keyword is used, the object will be created only when it is called, otherwise, there will be no object creation. lazy() is a function that takes a lambda and returns an instance of lazy which can serve as a delegate of lazy properties upon which it has been applied.
It has been designed to prevent the unnecessary initialization of objects.
- Lazy can be used only with non-NULLable variables.
- Variable can only be val. "var" is not allowed.
- Object will be initialized only once. Thereafter, you receive the value from the cache memory.
- The object will not be initialized until it has been used in the application.
class Demo {
val myName: String by lazy {
println("Welcome to Lazy declaration");
}
}
fun main() {
var obj=Demo();
println(obj.myName);
println("Second time call to the same object--"+obj.myName);
}
Comments
Post a Comment