Property delegation


#1

I want to do property delegation, but in a way different than the one the docs specify, and I want to know if it's possible at all

I have a Java class MyJavaClass with getters and setters for a property, let’s call it myProp. On my Kotlin class, I want to have a property that delegates to those getters/setters. So I want to have something like this:

public class MyClass(val obj:MyJavaClass) {   public var myPropDelegated:MyType by obj.myProp }

...or even...

public class MyClass(val obj:MyJavaClass) {   public var myPropDelegated:MyType   get = obj.myProp   set = obj.myProp }

... or something similar, without having to have real getter and setter code, which is short but a lot of boilerplate when you have lots of properties.

Is any of this possible or planned?


#2

I don't think exactly what you want but you can come close with a custom implementation that uses reflection. Your first example could look something like this:

public fun <T> KProperty<T>.get(thisRef: Any?, property: PropertyMetadata): T = this.get() 

That would (I think/untested) allow for:

public class MyClass(val obj:MyJavaClass) {
  public val myPropDelegated:MyType by obj::myProp
}

//end update

Your second example isn’t far away from a working example without delegation:

public class MyClass(val obj:MyJavaClass) {
  public var myPropDelegated:MyType
    get() = obj.myProp
    set(value) { obj.myProp = value }
}