gpt4 book ai didi

lambda - 试图了解Kotlin示例

转载 作者:行者123 更新时间:2023-12-02 13:04:23 25 4
gpt4 key购买 nike

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

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com