[英]Use of propertyName parameter in Delegates.observable
Kotlin中Delegates.observable的语法包括“ propertyName,oldValue和newValue”。
var name: String by Delegates.observable("no name") {
d, old, new ->
println("$old - $new")
}
但是,当我尝试对一组属性重用相同的可观察值时,它将无法正常工作。
例如
private val observablePropertyDelegate
= Delegates.observable("<none>")
{ pName, oldValue, newValue ->println("$pName is updated,$oldValue to $newValue")
}
var name: String by observablePropertyDelegate
var name1: String by observablePropertyDelegate
var name2: String by observablePropertyDelegate
令我困惑的是,如果我们不能为不同的属性重用Observable委托,那么为什么它包含属性名呢? 有什么特别的原因吗?
为什么不关注:
private val observablePropertyDelegate
= Delegates.observable("myOwnProperty","<none>")
{ oldValue, newValue ->println("myOwnProperty is updated,$oldValue to $newValue")
}
为什么说它不起作用?
这段代码:
import kotlin.properties.Delegates
class Test {
private val observablePropertyDelegate
= Delegates.observable("<none>")
{ pName, oldValue, newValue ->println("$pName is updated, $oldValue to $newValue")}
var name: String by observablePropertyDelegate
var name1: String by observablePropertyDelegate
var name2: String by observablePropertyDelegate
}
fun main(args: Array<String>) {
val test = Test()
test.name = "a"
test.name1 = "b"
test.name2 = "c"
test.name = "d"
test.name1 = "e"
test.name2 = "f"
}
输出此:
property name (Kotlin reflection is not available) is updated, <none> to a
property name1 (Kotlin reflection is not available) is updated, a to b
property name2 (Kotlin reflection is not available) is updated, b to c
property name (Kotlin reflection is not available) is updated, c to d
property name1 (Kotlin reflection is not available) is updated, d to e
property name2 (Kotlin reflection is not available) is updated, e to f
考虑到name
, name1
和name2
本质上是同一字段的别名,这对我来说似乎很好-这是相同的情况,就像您为mutiple属性使用相同的后备字段一样。
至于为什么将属性名称分配给委托人-您还如何知道使用哪个属性来访问该字段? 同样在您的第一个示例中,如果您更改属性名称,则委托仍会打印正确的消息。 但是在第二篇文章中,如果更改属性名称以使suer消息保持正确,则需要记住更新委托。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.