【问题标题】:Kotlin - Delegation chainKotlin - 委托链
【发布时间】:2018-06-08 15:46:52
【问题描述】:

在 Kotlin 中,是否可以有一个委托链? 为了演示我想要实现的目标,这是修改后的 kotlin 文档中的示例 (https://kotlinlang.org/docs/reference/delegation.html):

interface Base {
    fun print()
}

class BaseImpl(val x: Int) : Base {
    override fun print() { println(x) }
}

class Derived(var b: Base, val someData: Float = 10f) : Base by b

class SecondDerived(var b: Base) : Base by b

fun main(args: Array<String>) {
    val b = BaseImpl(10)
    val derived = Derived(b)
    val secondDerived: Base = SecondDerived(derived)
    secondDerived.print()// prints 10

    if (secondDerived is Derived) println(secondDerived.someData) //here secondDerived is Derived == false
}

我希望“secondDerived”属于“Derived”类型,但演员说不是。

我怀疑在内存中 secondDerived 基确实是 Derived 类型,但编译器看不到这一点。有什么办法可以让演员发挥作用吗?

【问题讨论】:

    标签: kotlin delegates


    【解决方案1】:

    在 JVM 上,一个类只能有一个超类,并且 Kotlin 的类委托不会以任何方式改变它。它所做的只是生成委托给Derived 实例的Base 接口方法的实现。它不影响is 检查。

    【讨论】:

      猜你喜欢
      • 2017-11-28
      • 2018-05-07
      • 1970-01-01
      • 2018-03-30
      • 2021-02-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多