Kotlin - 委托(delegate)链

标签 kotlin delegates

在 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/

相关文章:

ios - 子类化 MKMapView 并使其成为 mapview 委托(delegate),同时仍然允许其他委托(delegate)

C# 到 VB6 COM 事件 ("object or class does not support the set of events")

java - MediaSessionCompat :Targeting S+ (version 31 and above) requires that one of FLAG_IMMUTABLE or FLAG_MUTABLE be specified when creating a PendingIntent

android - 应用程序如何知道设备已经安装了该应用程序并将其从推荐奖金中消除?

android - 使用 Android Observer/Livedata/Coroutine/Kotlin 实现 Redux

ios - Swift 中的委托(delegate)方法, fatal error

objective-c - 在自定义 View 中重现 tableView 委托(delegate)行为

ios - 试图导出到 csv 但我如何从委托(delegate)中实现?

kotlin - 尝试在 intellij 中寻找 kotlin 字节码时修复 "No manual entry for byte\;type\=a"的最佳方法

android - :app:kaptDevDebugKotlin FAILED Build exception: cannot find symbol DataBindingComponent