Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Kotlin, is it possible to change delegation at Runtime?

Tags:

kotlin

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.

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
}

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

like image 792
ilkinulas Avatar asked Feb 20 '17 10:02

ilkinulas


1 Answers

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.

like image 154
yole Avatar answered Oct 05 '22 15:10

yole