What is lazy instantiation?

5

I saw here in the Wakim answer that code snippet:

data class Person(val firstName: String, val lastName: String) { 
    val fullName: String by lazy { "$firstName $lastName" } 
}

What is this lazy instantiation ?

    
asked by anonymous 12.08.2017 / 00:40

1 answer

6

This is a memo technique technique. So in this case you are declaring a property that has a get that will deliver the value defined there, in the "$firstName $lastName" case, however the value there is generated only once and does not have to be calculated every time you access the property, which in general it is a performance gain, even more if the information has to do a complex calculation or get information external to the application.

The example that the documentation shows is

val lazyValue: String by lazy {
    println("computed!")
    "Hello"
}

fun main(args: Array<String>) {
    println(lazyValue)
    println(lazyValue)
}

And the result is

computed!
Hello
Hello

Which 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() .

Documentation .

    
12.08.2017 / 01:08