试图理解 Kotlin 示例

Trying to understand Kotlin Example

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

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

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 值。 您还可以使用 return@label 指定显式 return。 在这种情况下:

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