在Kotlin,是否可以在运行时更改委派?

时间:2017-02-20 10:03:29

标签: kotlin

以下代码生成的字节代码在private final Base $$delegate_0类中创建Derived字段。分配可变字段b时,原始委托不会更改。

有没有办法在保持zero boilerplate实现的同时在运行时更改委托?

interface Base {
    fun print()
}

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

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

fun main(args: Array) {
    val b = BaseImpl(10)
    val derived = Derived(b)
    derived.print()// prints 10

    derived.b = BaseImpl(20)
    derived.print()// prints 10
}

样本来自文档https://kotlinlang.org/docs/reference/delegation.html并已编辑。

1 个答案:

答案 0 :(得分:9)

不,从版本1.1开始,Kotlin不支持此功能,但未来版本正在考虑这一点。这由this feature request跟踪。

相关问题