在 Kotlin 中,我们可以为非空属性定义一个 observable,
var name: String by Delegates.observable("<no name>") {
prop, old, new ->
println("$old -> $new")
}
这是不可能的
var name: String? by Delegates.observable("<no name>") {
prop, old, new ->
println("$old -> $new")
}
为可空属性定义可观察对象的方法是什么?
编辑:这是编译错误
Property delegate must have a 'setValue(DataEntryRepositoryImpl, KProperty<*>, String?)' method. None of the following functions is suitable:
public abstract operator fun setValue(thisRef: Any?, property: KProperty<*>, value: String): Unit defined in kotlin.properties.ReadWriteProperty
最佳答案
由于某种原因,类型推断在这里失败。您必须手动指定委托(delegate)的类型。相反,您可以省略属性类型声明:
var name by Delegates.observable<String?>("<no name>") {
prop, old, new ->
println("$old -> $new")
}
关于android - Kotlin:可空属性委托(delegate)可观察,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41536009/