Kotlin delegate property, In the get () method, how can I access the value?

Kotlin delegated properties, which is a very nice feature. But I figure out how to get and set the values. Let's say I want to get the value of a property that is delegated. In the get () method, how can I access the value?

Here is an example of how I implemented:

class Example() {
    var p: String by DelegateExample()
}
class DelegateExample {
    operator fun getValue(thisRef: Any?, property: KProperty<*>): String {
        return "${property.name} "
    }

  operator fun setValue(thisRef: Any?, property: KProperty<*>, value: String) {
    println("${value.trim()} '${property.name.toUpperCase()} '")
   }
}
fun delegate(): String {
    val e = Example()
    e.p = "NEW"
    return e.p
}

The main question that I cannot understand is how to set the value for the actual property to which the delegation class is assigned. When I assign the property "NEW" to a property p, how can I save this value to a variable por read this new value passed in pwith get? Am I losing something here? Any help would be much appreciated. Thanks in advance.

+4
1

,

class DelegateExample {

    private var value: String? = null        

    operator fun getValue(thisRef: Any?, property: KProperty<*>): String {
        return value ?: throw IllegalStateException("Initalize me!")
    }

    operator fun setValue(thisRef: Any?, property: KProperty<*>, value: String) {
        this.value = value
    }
}

- , get/set. , , Example ( → Kotlin → - Kotlin → ).

public final class Example {
   // $FF: synthetic field
   static final KProperty[] $$delegatedProperties = ...

   @NotNull
   private final DelegateExample p$delegate = new DelegateExample();

   @NotNull
   public final String getP() {
       return (String)this.p$delegate.getValue(this, $$delegatedProperties[0]);
   }

   public final void setP(@NotNull String var1) {
       Intrinsics.checkParameterIsNotNull(var1, "<set-?>");
       this.p$delegate.setValue(this, $$delegatedProperties[0], var1);
   }
}

, DelegateExample get/set,

+6

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


All Articles