Kotlin:可以为空的属性委托可观察

时间:2017-01-08 18:07:36

标签: android kotlin

在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

1 个答案:

答案 0 :(得分:40)

由于某种原因,类型推断失败了。您必须手动指定委托的类型。相反,您可以省略属性类型声明:

var name by Delegates.observable<String?>("<no name>") {
    prop, old, new ->
    println("$old -> $new")
}

请在https://youtrack.jetbrains.com/issues/KT

提交问题