Kotlin: How can I use delegated properties in Java?

Jire :

I know that you can't use the delegated property syntax in Java, and won't get the convenience of "overriding" the set/get operators as in Kotlin, but I'd still like to use an existing property delegate in Java.

For instance, a simple delegate of an int:

class IntDelegate {
    operator fun getValue(thisRef: Any?, property: KProperty<*>) = 0
}

In Kotlin of course we can use this like so:

val x by IntDelegate()

But how can we use IntDelegate in some form in Java? This is the start, I believe:

final IntDelegate x = new IntDelegate();

And then using the functions directly. But how can I use the getValue function? What do I pass for its parameters? How do I get a KProperty for Java field?

Ilya :

If you really want to know how Kotlin delegated property looks under the hood in Java, here it is: in this example a property x of a java class JavaClass is delegated to the Delegates.notNull standard delegate.

// delegation implementation details
import kotlin.jvm.JvmClassMappingKt;
import kotlin.jvm.internal.MutablePropertyReference1Impl;
import kotlin.jvm.internal.Reflection;
import kotlin.reflect.KProperty1;

// notNull property delegate from stdlib
import kotlin.properties.Delegates;
import kotlin.properties.ReadWriteProperty;


class JavaClass {
    private final ReadWriteProperty<Object, String> x_delegate = Delegates.INSTANCE.notNull();
    private final static KProperty1 x_property = Reflection.mutableProperty1(
            new MutablePropertyReference1Impl(
                JvmClassMappingKt.getKotlinClass(JavaClass.class), "x", "<no_signature>"));

    public String getX() {
        return x_delegate.getValue(this, x_property);
    }

    public void setX(String value) {
        x_delegate.setValue(this, x_property, value);
    }
}

class Usage {
    public static void main(String[] args) {
        JavaClass instance = new JavaClass();
        instance.setX("new value");
        System.out.println(instance.getX());
    }
}

However I wouldn't recommend to use this solution, not only because of the boilerplate required, but because it relies heavily on the implementation details of the delegated properties and kotlin reflection.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=471879&siteId=1