在Kotlin中,可以在运行时更改委派吗? [英] In Kotlin, is it possible to change delegation at Runtime?

查看:48
本文介绍了在Kotlin中,可以在运行时更改委派吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

The generated byte code for the below code creates a private final Base $$delegate_0 field in the Derived class. When the mutable field b is assigned the original delegate does not change.

是否有一种在保持zero boilerplate实现的同时在运行时更改委托的方法?

Is there a way to change the delegate at runtime while keeping the zero boilerplate implementation?


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
}

该示例摘自docs https://kotlinlang.org/docs/reference/delegation .html 并进行了编辑.

The sample is taken from the docs https://kotlinlang.org/docs/reference/delegation.html and edited.

推荐答案

否,Kotlin从1.1版开始不支持此功能,但是正在考虑将其用于将来的版本.这是由此功能请求跟踪的.

No, this is not supported in Kotlin as of version 1.1, but this is under consideration for a future version. This is tracked by this feature request.

这篇关于在Kotlin中,可以在运行时更改委派吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆