我想学习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)
字符串未分配给任何东西(字符串x =“my lazy”)或未在返回中使用
(返回“我的懒惰”)
有人可以解释吗? :)
最佳答案
Why is the println() only executed once?
发生这种情况是因为您是第一次访问它,它已创建。要创建,它将调用仅传递一次的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;
}
}
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)
Kotlin支持implicit returns用于lambda。这意味着将lambda的最后一条语句视为其返回值。
您还可以使用
return@label
指定显式返回。在这种情况下:
class LazySample {
val lazy: String by lazy {
println("computed!")
return@lazy "my lazy"
}
}
关于lambda - 试图了解Kotlin示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46573364/