In Kotlin can delegation be changed in Runtime?

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

Is there a way to change the delegate at runtime while maintaining 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 https://kotlinlang.org/docs/reference/delegation.html documents and edited.

+6
source share
1 answer

No, this is not supported in Kotlin since version 1.1, but it will be discussed in a future version. This is tracked by this feature request .

+9
source

Source: https://habr.com/ru/post/1015116/


All Articles