【问题标题】:Trying to understand Kotlin Example试图理解 Kotlin 示例
【发布时间】:2017-10-04 20:10:27
【问题描述】:

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

  • 我也对“我的懒惰”这句话感到困惑 字符串没有分配给任何东西(字符串 x =“我的懒惰”)或用于返回 (返回“我的懒惰”)

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

【问题讨论】:

    标签: lambda delegates kotlin lazy-sequences


    【解决方案1】:

    为什么 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 支持 implicit returns 用于 lambda。这意味着 lambda 的最后一条语句被视为它的返回值。 您还可以使用return@label 指定显式返回。 在这种情况下:

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

    【讨论】:

      猜你喜欢
      • 2021-01-16
      • 2023-03-05
      • 2019-03-07
      • 1970-01-01
      • 1970-01-01
      • 2012-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多