【发布时间】:2019-03-17 01:31:38
【问题描述】:
我很困惑委托在 Kotlin 中的工作方式。 Wikipedia 说:
借助对委托的语言级支持,这是通过让委托中的 self 引用原始(发送)对象而不是委托(接收对象)来隐式完成的。
给定以下代码:
interface BaseInterface {
fun print()
}
open class Base() : BaseInterface {
override fun print() { println(this) }
}
class Forwarded() {
private val base = Base()
fun print() { base.print() }
}
class Inherited() : Base() {}
class Delegated(delegate: BaseInterface) : BaseInterface by delegate
fun main(args: Array<String>) {
print("Forwarded: ")
Forwarded().print();
print("Inherited: ")
Inherited().print();
print("Delegated: ")
Delegated(Base()).print();
}
我得到这个输出:
Forwarded: Base@7440e464
Inherited: Inherited@49476842
Delegated: Base@78308db1
我希望 Delegated 返回 Delegated,因为 self/this 应该引用原始对象。是我弄错了还是 Kotlins 委托不同?
【问题讨论】:
-
我不认为 Wikipedia 的文章意味着带有该段落的 Kotlin(在有 Kotlin 示例之前它也存在)。不确定这是什么语言,但 Kotlin 没有。
-
我刚刚在this Wikipedia article 中找到了进一步的说明。似乎我确实将模式(从第一篇,不太清楚的 Wiki 文章)与编程概念(这篇文章)混淆了。所以 Kotlin 并没有实现委托的编程概念,而是实现了转发的概念。
-
在我澄清这个话题的地方查看我的答案。
标签: kotlin delegation