首页 > 解决方案 > 这不是指使用 Kotlins 类委托的原始对象

问题描述

我很困惑委托在 Kotlin 中的工作方式。维基百科说:

借助语言级别的委托支持,这是通过让委托中的 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 代表团不同?

标签: kotlindelegation

解决方案


Kotlin委托非常简单 - 它生成所有接口方法并在委托对象上隐式调用它,但用户显式覆盖的方法除外。

您的示例在功能上与:

class Delegated(delegate: BaseInterface) : BaseInterface{
    // when generating bytecode kotlin assigns delegate object to internal final variable
    // that is not visible at compile time
    private val d = delegate

    override fun print(){
        d.print()
    }
}

所以很清楚为什么会打印Base.


推荐阅读