5
I saw here on wakim’s response that code snippet:
data class Person(val firstName: String, val lastName: String) { val fullName: String by lazy { "$firstName $lastName" } }
What is this so-called Lazy instantiation?
5
I saw here on wakim’s response that code snippet:
data class Person(val firstName: String, val lastName: String) { val fullName: String by lazy { "$firstName $lastName" } }
What is this so-called Lazy instantiation?
6
This is a technique of memoisation. So in this case you’re declaring a property that owns a get
which will deliver the value defined there, in the case of "$firstName $lastName"
, however the value there is generated only once and does not need to be calculated every time you access the property, which in general is a performance gain, even more if the information has to make a complex calculation or take external information the application.
The example the documentation shows is
val lazyValue: String by lazy {
println("computed!")
"Hello"
}
fun main(args: Array<String>) {
println(lazyValue)
println(lazyValue)
}
Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.
And the result is
computed! Hello Hello
It shows that the function that generates the value is executed only once, but continues to produce the same result. This is achieved through the infrastructure already provided by <T> Lazy()
.
Browser other questions tagged property kotlin lazy-loading
You are not signed in. Login or sign up in order to post.
He thought memoization was the act of turning something into a meme. huehuh
– viana
That is memeization :)
– Maniero