Lambda 与 Receiver 的目的是什么? [英] What is a purpose of Lambda's with Receiver?
问题描述
在 Kotlin 中使用接收器的 Lambda 的目的是什么,而我们有扩展功能?
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.
对此有很多很好的用例(请参阅DSLs特别),但我将在这里举一个简单的例子.
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屋!