Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin delegation to expression instead of fixed reference

Suppose I have a very intricate specification defined as an interface:

interface Spec {
    fun sayHello()
}

And a standard implementation:

class Impl(private val msg: String) : Spec {
    override fun sayHello() {
        println(msg)
    }
}

Now suppose that I want to create a class that implements this specification and delegates to an implementation, but the exact delegate object is mutable throughout the object's lifetime. Here's an example:

class Derived(var target: Spec) : Spec by target

The problem with the above example is that the constructor argument target is set as the delegate object when the constructor is called. The delegate is then accessed by the class directly instead of performing a property access. (This has been confirmed by looking through the bytecode produced by Kotlin.)

So, even if the property target is modified after the class is constructed, the delegate does not change.

Can anybody provide a method for performing this delegation in Kotlin without having to write out every single method?

An ideal solution would also allow for delegation to something as general as a lambda or other expression that would be evaluated and used as the delegate whenever the delegate is needed throughout the lifetime of the object.

like image 262
Parker Hoyes Avatar asked May 03 '16 00:05

Parker Hoyes


1 Answers

Right now there is no way to do that. See Kotlin issue KT-5870

Currenlty Kotlin evaluates expression for delegate in class initializer

like image 183
D3xter Avatar answered Oct 19 '22 17:10

D3xter