[英]kotlin delegate property ,In a get() method how i can access the value?
Kotlin has delegated properties which is a very nice feature. Kotlin委托了属性,这是一个非常好的功能。 But I am figuring out how to get and set the values.
但我正在弄清楚如何获取和设置值。 Let's say I want to get value of the property which is delegated.
假设我想获得委托的财产的价值。 In a get() method how i can access the value?
在get()方法中我如何访问该值?
Here's an example of how I have 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 I am unable to understand is, How can I set the value to the actual property on which the delegation class is assigned. 我无法理解的主要问题是,如何将值设置为分配了委托类的实际属性。 When I assign "NEW" to property
p
, how can I store that value to the variable p
or read that new value passed on to p
with get? 当我为属性
p
分配“NEW”时,如何将该值存储到变量p
或读取传递给p
新值? Am I missing something basic here? 我错过了一些基本的东西吗? Any help will be much appreciated.
任何帮助都感激不尽。 Thanks in advance.
提前致谢。
Just create property in delegate which will hold the value 只需在委托中创建属性即可保存该值
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
}
}
To clarify - delegates aren't values holder, they are handlers of get
/ set
operations. 为了澄清 - 代表不是价值持有者,他们是
get
/ set
操作的处理者。 You can take a look how it works under the hood if you decompile your Example
class (Tools -> Kotlin -> Show Kotlin bytecode -> Decompile). 如果你反编译你的
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);
}
}
No magic here, just creating instance of the DelegateExample
and its get
/ set
method invoking 这里没有魔法,只需创建
DelegateExample
实例及其get
/ set
方法调用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.