【发布时间】: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 类型,但编译器看不到这一点。有什么办法可以让演员发挥作用吗?
【问题讨论】: