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")
}
答案 0 :(得分:1)
您为什么说它不起作用?
此代码:
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
本质上是同一字段的别名,这对我来说似乎很好-这就像您为多个属性使用相同的后备字段一样
至于为何将属性名称分配给委托人-您还如何知道使用哪个属性来访问字段?同样在您的第一个示例中,如果您更改属性名称,则委托仍会打印正确的消息。但是在第二篇文章中,如果更改属性名称以使suer消息保持正确,则需要记住更新委托。