在 Kotlin 中,是否可以有一个委托(delegate)链?
为了演示我想要实现的目标,这是修改后的 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”类型,但 Actor 说不是。
我怀疑在内存中 secondDerived 基确实是 Derived 类型,但编译器看不到这一点。有什么办法可以让 Actor 工作吗?
最佳答案
在 JVM 上,一个类只能有一个父类(super class),而 Kotlin 的类委托(delegate)不会以任何方式改变它。它所做的只是生成 Base
的实现委托(delegate)给 Derived
的接口(interface)方法实例。不影响is
检查。
关于Kotlin - 委托(delegate)链,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50755616/