Kotlin: How can I use delegated properties in Java?

I know that you cannot use delegated property syntax in Java and do not get the convenience of "overriding" the set / get statements, as in Kotlin, but I would still like to use the existing property delegate in Java.

For example, a simple int delegate:

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

In Kotlin, of course, we can use it like this:

 val x by IntDelegate() 

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

 final IntDelegate x = new IntDelegate(); 

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

+5
source share
2 answers

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

 // 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 would not recommend using this solution not only because of the required template, but also because it largely depends on the implementation details of the delegated properties and the reflection of the kotlin.

+3
source

I know that you cannot use delegated property syntax in Java and do not get the convenience of "overriding" the set / get statements, as in Kotlin, but I would still like to use the existing property delegate in Java.

No, just like you said at the beginning, it is not in Java. But if you insist on it, you can do such things.

 public interface Delegate<T> { T get(); void set(T value); } public class IntDelegate implements Delegate<Integer> { private Integer value = null; @Override public void set(Integer value) { this.value = value; } @Override public Integer get() { return value; } } final Delegate<Integer> x = new IntDelegate(); 

Delcare x in the interface allows you to have a different implementation.

+1
source

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


All Articles