试图了解Kotlin示例

我想学习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()只执行一次?

  • 我也对“我的懒惰”字符串没有分配给任何东西(字符串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; } } 

我也对“我的懒惰”字符串没有分配给任何东西(字符串x =“我的懒惰”)或用于返回(返回“我的懒惰”

Kotlin支持lambda的隐式返回 。 这意味着lambda的最后一个语句被认为是它的返回值。 你也可以用return@label指定一个显式的返回值。 在这种情况下:

 class LazySample { val lazy: String by lazy { println("computed!") return@lazy "my lazy" } }