Lambda与Receiver的目的是什么? [英] What is a purpose of Lambda's with Receiver?
问题描述
虽然Kotlin具有扩展功能,但Lambda与Receiver在Kotlin中的用途是什么?
What is a purpose of Lambda's with Receiver in Kotlin, while we have extension functions ?
下面的两个函数具有相同的作用,但是第一个函数更易读且简短:
Two functions below do the same things, however first one is more readable and short:
fun main(args: Array<String>) {
println("123".represents(123))
println(123.represents("123"))
}
fun String.represents(another: Int) = toIntOrNull() == another
val represents: Int.(String) -> Boolean = {this == it.toIntOrNull()}
推荐答案
带有接收器的Lambda基本上与扩展函数相同,它们只能存储在属性中并传递给函数.这个问题本质上与当我们有函数时lambda的目的是什么?"相同.答案也大致相同-它使您可以在代码中的任何地方快速创建匿名扩展功能.
Lambdas with receivers are basically exactly the same as extension functions, they're just able to be stored in properties, and passed around to functions. This question is essentially the same as "What's the purpose of lambdas when we have functions?". The answer is much the same as well - it allows you to quickly create anonymous extension functions anywhere in your code.
对此有很多很好的用例(请参阅《 DSL》中的 DSL 特别是),但在这里我将举一个简单的例子.
There are many good use cases for this (see DSLs in particular), but I'll give one simple example here.
例如,假设您有一个像这样的函数:
For instance, let's say you have a function like this:
fun buildString(actions: StringBuilder.() -> Unit): String {
val builder = StringBuilder()
builder.actions()
return builder.toString()
}
调用此函数将如下所示:
Calling this function would look like this:
val str = buildString {
append("Hello")
append(" ")
append("world")
}
启用此语言功能有一些有趣的事情:
There are a couple interesting things this language feature enabled:
- 在传递给
buildString
的lambda内,您处于新的作用域,因此有新的方法和属性可供使用.在这种情况下,您可以使用StringBuilder
类型的方法,而不必在任何实例上调用它们. - 要对这些函数进行调用的实际
StringBuilder
实例不受您管理-由函数的内部实现来创建一个并在其上调用您的扩展函数.
因此, - 此函数还可以做很多事情,而不仅仅是一次在一个
StringBuilder
上调用传递给它的lambda-它可以多次调用,在各种StringBuilder
实例上,将其存储为以后使用,等等.
- Inside the lambda you pass to
buildString
, you're in a new scope and as such have new methods and properties available for use. In this specific case, you can use methods on theStringBuilder
type without having to call them on any instance. - The actual
StringBuilder
instance these function calls are going to be made on is not managed by you - it's up to the internal implementation of the function to create one and call your extension function on it. - Consequently, it would also be possible for this function to do much more than just call the lambda you passed to it once on one
StringBuilder
- it could call it multiple times, on variousStringBuilder
instances, store it for later use, etc.
这篇关于Lambda与Receiver的目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!