试图了解Kotlin示例

时间:2017-10-04 20:10:28

标签: lambda delegates kotlin lazy-sequences

我想学习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

我不知道这里发生了什么。 (可能是因为我对lambdas并不熟悉)

  • 为什么println()只执行一次?

  • 我也对“懒惰”这一行感到困惑 String未分配给任何内容(String x =“my lazy”)或在返回中使用 (返回“我的懒惰”

有人可以解释一下吗? :)

1 个答案:

答案 0 :(得分:5)

  

为什么println()只执行一次?

这是因为第一次访问它时会创建它。要创建它,它会调用您只传递一次的lambda并指定值tearDown。 您在"my lazy"中编写的代码与此java代码相同:

Kotlin
  

我也对“我的懒”字符串未分配的行感到困惑   任何事物(字符串x =“我的懒惰”)或用于返回(返回“我的   懒惰)

Kotlin为lambda支持implicit returns。这意味着lambda的最后一个语句被认为是它的返回值。 您还可以使用public class LazySample { private String lazy; private String getLazy() { if (lazy == null) { System.out.println("computed!"); lazy = "my lazy"; } return lazy; } } 指定显式返回。 在这种情况下:

return@label
相关问题