"receiver object"和"extension receiver"有区别吗
Is there any difference between "receiver object" and "extension receiver"
根据文档很难判断https://kotlinlang.org/docs/reference/extensions.html
所以我想知道 receiver object 和 extension receiver 是一样的吗?还是名称取决于上下文?
扩展接收器是一个接收器对象,而接收器对象是调度接收器或分机接收器。
Inside a class, you can declare extensions for another class. Inside such an extension, there are multiple implicit receivers - objects members of which can be accessed without a qualifier. The instance of the class in which the extension is declared is called dispatch receiver, and the instance of the receiver type of the extension method is called extension receiver.
class D {
fun bar() { ... }
}
class C {
fun baz() { ... }
fun D.foo() {
bar() // calls D.bar
baz() // calls C.baz
}
fun caller(d: D) {
d.foo() // call the extension function
}
}
在上面的示例中,函数 foo
有两个 隐式接收器 :C
是 调度接收器 D
是 分机接收者 。如果 foo
在 class C
之外声明,那么它将只有一个接收器,即 扩展接收器 D
.
简而言之,接收者对象和扩展接收者可以是相同的,但还有另一种类型的receiver object 调用了 dispatch receiver.
有关详细信息,请参阅 Declaring Extensions as Members - Extensions - Kotlin Programming Language。
根据文档很难判断https://kotlinlang.org/docs/reference/extensions.html
所以我想知道 receiver object 和 extension receiver 是一样的吗?还是名称取决于上下文?
扩展接收器是一个接收器对象,而接收器对象是调度接收器或分机接收器。
Inside a class, you can declare extensions for another class. Inside such an extension, there are multiple implicit receivers - objects members of which can be accessed without a qualifier. The instance of the class in which the extension is declared is called dispatch receiver, and the instance of the receiver type of the extension method is called extension receiver.
class D { fun bar() { ... } } class C { fun baz() { ... } fun D.foo() { bar() // calls D.bar baz() // calls C.baz } fun caller(d: D) { d.foo() // call the extension function } }
在上面的示例中,函数 foo
有两个 隐式接收器 :C
是 调度接收器 D
是 分机接收者 。如果 foo
在 class C
之外声明,那么它将只有一个接收器,即 扩展接收器 D
.
简而言之,接收者对象和扩展接收者可以是相同的,但还有另一种类型的receiver object 调用了 dispatch receiver.
有关详细信息,请参阅 Declaring Extensions as Members - Extensions - Kotlin Programming Language。