lambda - 试图了解Kotlin示例

标签 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

我不明白这里发生了什么。 (可能是因为我不太熟悉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/

    相关文章:

    Android - 如何使用数据绑定(bind)从 XML 传递 View 对象

    c# - 如何 : "letrec" in C# (lambda expression call within its definition)

    c#-4.0 - 性能问题 : How to execute Two lambda expression at once?。使用了 "Contains"和 "Any"运算符

    c# - Lambda 表达式 : Where clause for Include list

    ios - iBeacon:didRangeBeacons 停止被调用,必须重置设备才能再次工作

    android - 如何在多个 Activity 中使用 Android Nearby Connections

    c# - Func<> 有 2 个输出值

    ios - 委托(delegate)如何知道在有多个一致性的地方调用函数

    c# - 在多个订阅者的情况下,委托(delegate)如何知道调用哪个函数

    java - GraphQL Java 未正确检测 kotlin 枚举