在Kotlin中,Delegates.observable的语法由"propertyName,oldValue,newValue“组成。
var name: String by Delegates.observable("no name") {
d, old, new ->
println("$old - $new")
}但是,当我尝试对一系列属性重用相同的可观察对象时,它将不起作用。
e.g
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让我困惑的是,如果我们不能为不同的属性重用可观察的委托,那么为什么它包含属性名称?有什么特别的原因吗?
为什么不遵循以下原则:
private val observablePropertyDelegate
= Delegates.observable("myOwnProperty","<none>")
{ oldValue, newValue ->println("myOwnProperty is updated,$oldValue to $newValue")
}发布于 2018-06-22 19:09:22
为什么你说它不起作用?
这段代码:
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消息保持正确。
https://stackoverflow.com/questions/50986074
复制相似问题