Kotlin 中的这段代码“懒惰”是什么意思?

Ilk*_*ada 1 syntax lazy-evaluation kotlin

这段代码是做什么的?

fun<T:x>a.b(y: Int)=lazy{u.v<T>(y)}
Run Code Online (Sandbox Code Playgroud)

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

dom*_*der 6

fun<T:x>ab(y: Int)=lazy{uv(y)}

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

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

现在,让我们一点一点。

fun 意味着我们要声明一个新方法。

<T:x>意味着这是一个对类型T进行操作的泛型方法,whereT限制为 type x

a.b意味着这是一个以type命名的扩展函数ba

(y: Int)意味着定义的函数b采用一个名为ytype 的参数Int

=表达式主体语法- 返回短代码行的简写。这意味着a.b将返回作为评估结果的值lazy { }

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

{ u.v<T>(y) }是该Lazy对象第一次获取其值时将执行的函数,并将其返回值u.v<T>(y)保存为惰性对象的value.

呼!那是什么意思呢?让我们看一个例子。假设我们在函数中添加了一个打印语句以查看它何时被调用。

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

现在,如果您尝试使用它:

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)  
}
Run Code Online (Sandbox Code Playgroud)

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

希望有帮助!