I want to learn Kotlin and am working through the Examples on try.kotlinlang.org
I have trouble understanding some examples, particularly the Lazy property example: https://try.kotlinlang.org/#/Examples/Delegated%20properties/Lazy%20property/Lazy%20property.kt
/**
* Delegates.lazy() is a function that returns a delegate that implements a lazy property:
* the first call to get() executes the lambda expression passed to lazy() as an argument
* and remembers the result, subsequent calls to get() simply return the remembered result.
* If you want thread safety, use blockingLazy() instead: it guarantees that the values will
* be computed only in one thread, and that all threads will see the same value.
*/
class LazySample {
val lazy: String by lazy {
println("computed!")
"my lazy"
}
}
fun main(args: Array<String>) {
val sample = LazySample()
println("lazy = ${sample.lazy}")
println("lazy = ${sample.lazy}")
}
Output:
computed!
lazy = my lazy
lazy = my lazy
I don't get what is happening here. (probably because I am not really familiar with lambdas)
Why is the println() only executed once?
I am also confused about the line "my lazy" the String isn't assigned to anything (String x = "my lazy") or used in a return (return "my lazy)
Can someone explain please? :)