在Kotlin中,我们可以为非null属性定义一个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")
}
为可空属性定义observable的方法是什么?
编辑:这是编译错误
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
答案 0 :(得分:40)
由于某种原因,类型推断失败了。您必须手动指定委托的类型。相反,您可以省略属性类型声明:
var name by Delegates.observable<String?>("<no name>") {
prop, old, new ->
println("$old -> $new")
}
提交问题