本文介绍了什么是“接收器"?在科特林?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

它和扩展函数有什么关系?为什么 with 一个函数,不是关键字?

How is it related to extension functions? Why is with a function, not a keyword?

该主题似乎没有明确的文档,只有参考 扩展的知识假设.

There appears to be no explicit documentation for this topic, only the assumption of knowledge in reference to extensions.

推荐答案

确实,关于接收器概念的现有文档似乎很少(只有一个 与扩展函数相关的小附注),这是令人惊讶的:

It is true that there appears to be little existing documentation for the concept of receivers (only a small side note related to extension functions), which is surprising given:

  • their existence springing out of extension functions;
  • their role in building a DSL using said extension functions;
  • the existence of a standard library function with, which given no knowledge of receivers might look like a keyword;
  • a completely separate syntax for function types.

所有这些主题都有文档,但没有深入介绍接收器.

All these topics have documentation, but nothing goes in-depth on receivers.

首先:

Kotlin 中的任何代码块都可能有一个类型(甚至多种类型)作为接收器,使接收器的功能和属性在该代码块中可用,而无需对其进行限定.

Any block of code in Kotlin may have a type (or even multiple types) as a receiver, making functions and properties of the receiver available in that block of code without qualifying it.

想象一下这样的代码块:

Imagine a block of code like this:

{ toLong() }

没有多大意义,对吧?实际上,将其分配给 (Int) ->Long - 其中 Int 是(唯一的)参数,返回类型是 Long - 会导致编译错误.您可以通过简单地使用隐式单参数限定函数调用来解决此问题 it.但是,对于 DSL 构建,这会导致一系列问题:

Doesn't make much sense, right? In fact, assigning this to a function type of (Int) -> Long - where Int is the (only) parameter, and the return type is Long - would rightfully result in a compilation error. You can fix this by simply qualifying the function call with the implicit single parameter it. However, for DSL building, this will cause a bunch of issues:

  • 嵌套的 DSL 块将隐藏其上层:
    html { it.body {//这里如何访问 html 的扩展?} ... }
    这可能不会导致 HTML DSL 出现问题,但可能会导致其他用例出现问题.
  • 它可能会因 it 调用而乱扔代码,尤其是对于经常使用其参数(即将成为接收器)的 lambda.
  • Nested blocks of DSL will have their upper layers shadowed:
    html { it.body { // how to access extensions of html here? } ... }
    This may not cause issues for a HTML DSL, but may for other use cases.
  • It can litter the code with it calls, especially for lambdas that use their parameter (soon to be receiver) a lot.

这是接收器发挥作用的地方.

通过将此代码块分配给具有 Int 作为接收器(不是作为参数!)的函数类型,代码突然编译:

By assigning this block of code to a function type that has Int as a receiver (not as a parameter!), the code suddenly compiles:

val intToLong: Int.() -> Long = { toLong() }

这是怎么回事?

本主题假设您熟悉函数类型,但有一点点需要接收者注意.

This topic assumes familiarity with function types, but a little side note for receivers is needed.

函数类型也可以有一个接收器,通过在它前面加上类型和一个点.示例:

Function types can also have one receiver, by prefixing it with the type and a dot. Examples:

Int.() -> Long  // taking an integer as receiver producing a long
String.(Long) -> String // taking a string as receiver and long as parameter producing a string
GUI.() -> Unit // taking an GUI and producing nothing

此类函数类型的参数列表以接收器类型为前缀.

Such function types have their parameter list prefixed with the receiver type.

理解如何处理带有接收器的代码块实际上非常容易:

It is actually incredibly easy to understand how blocks of code with receivers are handled:

想象一下,类似于扩展函数,代码块在接收器类型的类中进行评估.this 实际上被接收器类型修改了.

Imagine that, similar to extension functions, the block of code is evaluated inside the class of the receiver type. this effectively becomes amended by the receiver type.

对于我们之前的示例,val intToLong: Int.() ->Long = { toLong() } ,它有效地导致在不同的上下文中评估代码块,就好像它被放置在 Int 内的函数中.下面是一个使用手工制作类型的不同示例,可以更好地展示这一点:

For our earlier example, val intToLong: Int.() -> Long = { toLong() } , it effectively results in the block of code being evaluated in a different context, as if it was placed in a function inside Int. Here's a different example using handcrafted types that showcases this better:

class Bar

class Foo {
    fun transformToBar(): Bar = TODO()
}

val myBlockOfCodeWithReceiverFoo: (Foo).() -> Bar = { transformToBar() }

有效地变成(在头脑中,不是代码明智的 - 你实际上不能在 JVM 上扩展类):

effectively becomes (in the mind, not code wise - you cannot actually extend classes on the JVM):

class Bar

class Foo {
    fun transformToBar(): Bar = TODO()

    fun myBlockOfCode(): Bar { return transformToBar() }
}

val myBlockOfCodeWithReceiverFoo: (Foo) -> Bar = { it.myBlockOfCode() }

注意在类内部,我们不需要使用 this 来访问 transformToBar - 同样的事情发生在带有接收器的块中.

Notice how inside of a class, we don't need to use this to access transformToBar - the same thing happens in a block with a receiver.

碰巧关于this的文档也解释了如何使用如果当前代码块有两个接收器,则为最外层接收器,通过 限定此.

It just so happens that the documentation on this also explains how to use an outermost receiver if the current block of code has two receivers, via a qualified this.

是的.一个代码块可以有多个接收器,但目前在类型系统中没有表达式.实现这一点的唯一方法是通过多个 高阶函数,这些函数采用单个接收器函数类型.示例:

Yes. A block of code can have multiple receivers, but this currently has no expression in the type system. The only way to achieve this is via multiple higher-order functions that take a single receiver function type. Example:

class Foo
class Bar

fun Foo.functionInFoo(): Unit = TODO()
fun Bar.functionInBar(): Unit = TODO()

inline fun higherOrderFunctionTakingFoo(body: (Foo).() -> Unit) = body(Foo())
inline fun higherOrderFunctionTakingBar(body: (Bar).() -> Unit) = body(Bar())

fun example() {
    higherOrderFunctionTakingFoo {
        higherOrderFunctionTakingBar {
            functionInFoo()
            functionInBar()
        }
    }
}

请注意,如果 Kotlin 语言的此功能似乎不适合您的 DSL,@DslMarker 是你的朋友!

Do note that if this feature of the Kotlin language seems inappropriate for your DSL, @DslMarker is your friend!

为什么这一切都很重要?有了这些知识:

Why does all of this matter? With this knowledge:

  • 您现在明白为什么可以在数字的扩展函数中编写 toLong() 而不必以某种方式引用该数字.也许你的扩展函数不应该是扩展?
  • 您可以为自己喜欢的标记语言构建一个 DSL,也许有助于解析其中一种语言(谁需要正则表达式?!).
  • 你明白为什么 with,一个标准库函数而不是一个关键字,存在 - 修改代码块的范围以节省冗余类型的行为是如此普遍,语言设计者把它放在标准库中.
  • (也许)您在分支中学到了一些关于函数类型的知识.
  • you now understand why you can write toLong() in an extension function on a number, instead of having to reference the number somehow. Maybe your extension function shouldn't be an extension?
  • You can build a DSL for your favorite markup language, maybe help parsing the one or other (who needs regular expressions?!).
  • You understand why with, a standard library function and not a keyword, exists - the act of amending the scope of a block of code to save on redundant typing is so common, the language designers put it right in the standard library.
  • (maybe) you learned a bit about function types on the offshoot.

这篇关于什么是“接收器"?在科特林?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 05:31