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.
Right now there is no way to do that. See Kotlin issue KT-5870
Currenlty Kotlin evaluates expression for delegate in class initializer
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With