Kotlin Delayed Initialization (lateinit, by lazy)
lateinit
A class property must normally be initialized, but initialization can be delayed with lateinit.
It cannot be used with primitive types such as Int, nullable types, or anything other than a var property.
class Foo {
lateinit var name: String // Initialization is required before init() is called
fun init(name: String) { this.name = name }
}
by lazy
by lazy is similar to lateinit. It can be used with Int and nullable types, but only with val properties.
The declaration includes a lambda expression for initialization.
The value is initialized when it is first needed, that is, when it is referenced for the first time.
It is useful when an object such as a database connection should be initialized only once.
fun connectToDB() {
...
return db
}
fun main() {
val db by lazy { connectToDB() }
}
Let’s write and run a simple example to check that initialization really happens only once.
class ByLazy {
val greeting: String by lazy {
println("Greeting is Initialized!!!!") // Runs only once.
"Hello"
}
}
fun main() {
val byLazy = ByLazy()
println("Greeting is Not Initialized")
println("Greeting one : ${byLazy.greeting}")
println("Greeting two : ${byLazy.greeting}")
println("Greeting three : ${byLazy.greeting}")
}
Output:
Greeting is Not Initialized
Greeting is Initialized!!!!
Greeting one : Hello
Greeting two : Hello
Greeting three : Hello
The result shows that "Greeting is Initialized!!!!" is printed only the first time the greeting property is read, and not on subsequent reads.