Pri*_*iya 6 android delegates kotlin
Kotlin委托了属性,这是一个非常好的功能.但我正在弄清楚如何获取和设置值.假设我想获得委托的财产的价值.在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()
e.p = "NEW"
return e.p
}
Run Code Online (Sandbox Code Playgroud)
我无法理解的主要问题是,如何将值设置为分配了委托类的实际属性.当我为属性分配"NEW"时p,如何将该值存储到变量p或读取传递给pget的新值?我错过了一些基本的东西吗?任何帮助都感激不尽.提前致谢.
只需在委托中创建属性即可保存该值
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
}
}
Run Code Online (Sandbox Code Playgroud)
澄清 - 代表不是价值持有者,他们是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);
}
}
Run Code Online (Sandbox Code Playgroud)
这里没有魔法,只是创建了DelegateExample它的实例和它的get/ set方法调用
| 归档时间: |
|
| 查看次数: |
608 次 |
| 最近记录: |