kotlin委托属性,在get()方法中,我可以如何访问值?

Kotlin已经委派了属性,这是一个非常好的function。 但是我正在弄清楚如何获取和设置值。 假设我想获得委托的财产的价值。 在get()方法中,我可以如何访问该值?

以下是我已经实现的一个例子:

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() ep = "NEW" return ep } 

我无法理解的主要问题是,如何将值设置为委派类所属的实际属性。 当我给属性p分配“NEW”时,如何将该值存储到variablesp或者读取通过get传递给p新值? 我在这里错过什么基本的东西? 任何帮助都感激不尽。 提前致谢。

只需在委托中创建属性即可保存值

 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类(Tools – > Kotlin – > Show Kotlin bytecode – > Decompile),你可以看看它是如何工作的。

 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, ""); this.p$delegate.setValue(this, $$delegatedProperties[0], var1); } } 

这里没有什么魔力,只是创建DelegateExample实例和它的get / set方法调用