Kotlin - 代表团链

时间:2018-06-08 07:34:00

标签: kotlin delegates

在Kotlin,是否有可能拥有代表团链? 为了证明我想要实现的目标是kotlin doc修改的示例(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类型,但编译器无法看到。有没有办法让演员工作?

1 个答案:

答案 0 :(得分:2)

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

相关问题