以下代码生成的字节代码在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并已编辑。