[英]Trying to understand Kotlin Example
我想学习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
我不明白这里发生了什么。 (可能是因为我不太熟悉lambda)
为什么println()只执行一次?
我也对行“ my lazy”感到困惑,该字符串未分配给任何东西(String x =“ my lazy”)或未在返回中使用(返回“ my lazy”)
有人可以解释吗? :)
为什么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;
}
}
我也对行“ my lazy”感到困惑,该字符串未分配给任何东西(String x =“ my lazy”)或未在返回中使用(返回“ my lazy”)
Kotlin支持lambda的隐式返回 。 这意味着将lambda的最后一条语句视为其返回值。 您还可以使用return@label
指定显式的收益。 在这种情况下:
class LazySample {
val lazy: String by lazy {
println("computed!")
return@lazy "my lazy"
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.