【发布时间】:2017-10-04 20:10:27
【问题描述】:
我想学习 Kotlin,并且正在研究 try.kotlinlang.org
我无法理解一些示例,尤其是 Lazy 属性示例: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}")
}
输出:
computed!
lazy = my lazy
lazy = my lazy
我不明白这里发生了什么。 (可能是因为我对 lambdas 不是很熟悉)
为什么println()只执行一次?
我也对“我的懒惰”这句话感到困惑 字符串没有分配给任何东西(字符串 x =“我的懒惰”)或用于返回 (返回“我的懒惰”)
有人可以解释一下吗? :)
【问题讨论】:
标签: lambda delegates kotlin lazy-sequences