abi*_*rth 1 lambda delegates lazy-sequences kotlin
我想学习Kotlin并正在研究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}")
}
Run Code Online (Sandbox Code Playgroud)
输出:
computed!
lazy = my lazy
lazy = my lazy
Run Code Online (Sandbox Code Playgroud)
我不知道这里发生了什么.(可能是因为我对lambdas并不熟悉)
为什么println()只执行一次?
我也很困惑"我的懒"字符串没有分配给任何东西(字符串x ="我的懒惰")或用于返回(返回"我的懒惰")
有人可以解释一下吗?:)
为什么println()只执行一次?
发生这种情况是因为您第一次访问它时会创建它.要创建它,它会调用您只传递一次的lambda并分配值"my lazy".您编写的代码Kotlin与此java代码相同:
public class LazySample {
private String lazy;
private String getLazy() {
if (lazy == null) {
System.out.println("computed!");
lazy = "my lazy";
}
return lazy;
}
}
Run Code Online (Sandbox Code Playgroud)
我也很困惑"我的懒"字符串没有分配给任何东西(字符串x ="我的懒惰")或用于返回(返回"我的懒惰")
Kotlin支持lambda的隐式返回.这意味着lambda的最后一个语句被认为是它的返回值.您还可以使用指定显式返回return@label.在这种情况下:
class LazySample {
val lazy: String by lazy {
println("computed!")
return@lazy "my lazy"
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
236 次 |
| 最近记录: |