【问题标题】:What does "lazy" mean with this code in Kotlin?Kotlin 中这段代码的“懒惰”是什么意思?
【发布时间】:2020-06-21 21:29:54
【问题描述】:

这段代码在做什么?

fun<T:x>a.b(y: Int)=lazy{u.v<T>(y)}

我不知道“懒惰”在做什么,或者“懒惰”在 Kotlin 中是什么特别的东西。

【问题讨论】:

  • 搜索"kotlin lazy keyword"。文档(通常通过搜索找到)是解决此类问题的好地方。
  • @user2864740 我看了,还是看不懂整行。

标签: kotlin syntax lazy-evaluation


【解决方案1】:

funa.b(y: Int)=lazy{u.v(y)}

让我们分解一下。首先,让我们重新格式化以提高可读性:)

fun &lt;T: x&gt; a.b(y: Int) = lazy { u.v&lt;T&gt;(y) }

现在,让我们一块一块地去吧。

fun 表示我们正在声明一个新方法。

&lt;T:x&gt; 表示这是对T 类型进行操作的泛型方法,其中Tconstrained,属于x 类型。

a.b 表示这是一个名为 bextension function,类型为 a

(y: Int) 表示定义的函数b 接受一个名为yInt 类型的参数。

=expression body syntax - 返回一小段代码的简写。这意味着a.b 将返回作为评估lazy { } 的结果的值

lazya Kotlin standard library function 延迟对提供给它的函数的评估,直到需要它,然后缓存结果。这个函数的返回值实际上是一个类型Lazy,它包装了提供的函数。

{ u.v&lt;T&gt;(y) }Lazy对象第一次获取值时执行的函数,u.v&lt;T&gt;(y)的返回值会保存为惰性对象的value

呸!那是什么意思?让我们看一个例子。假设我们在函数中添加一个 print 语句来查看它何时被调用。

fun <T: x> a.b(y: Int) = lazy {
  println("Executing 'b'")
  u.v<T>(y)
}

现在如果你尝试使用它:

fun main() {
  val a = A<T>() // Assume some type T
  val lazyObject = a.b<T>(42) // Call the extension method that returns a `Lazy`
  
  // Get the value from the lazy object - prints "Executing 'b'",
  // executes `u.v<T>(y)`, caches the result, returns it - then print it
  println(lazyObject.value) 
 
  // Get the value from the lazy object again. This time, DOES NOT print
  // "Executing 'b'", DOES NOT execute `u.v<T>(y)`, and just returns the
  // result that was already computed and cached, then print it
  println(lazyObject.value)  
}

因此,总而言之,您发布的代码正在创建一个 extension 方法,该方法返回一个 Lazy 对象,当查询它的值时,执行它初始化的 lambda 并缓存结果以后再用。

希望有帮助!

【讨论】:

    猜你喜欢
    • 2016-12-18
    • 1970-01-01
    • 2016-03-28
    • 1970-01-01
    相关资源
    最近更新 更多