我想學習科特林和我通過實例對工作 try.kotlinlang.org試圖瞭解科特林例
我聽不太懂一些例子,特別是懶惰的屬性例如: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
我不明白這裏發生了什麼。 (可能是因爲我不熟悉lambda)
爲什麼println()只執行一次?
我也困惑行「我懶」 字符串沒有分配到任何東西(串x =「我的懶惰」),或在返回 使用(返回「我的懶惰)
有人能解釋嗎?:)