android - Kotlin:可空属性委托(delegate)可观察

标签 android kotlin

在 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")
}

请在 https://youtrack.jetbrains.com/issues/KT 提出问题

关于android - Kotlin:可空属性委托(delegate)可观察,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41536009/

相关文章:

android - 在 PopBackStack 上保留数据

class - Kotlin 为枚举类值方法定义接口(interface)

java - 单击通知时如何将 Activity 显示为弹出 Intent ?

android获取当前位置

java.lang.ClassCastException : android. support.constraint.ConstraintLayout 无法转换为 android.widget.TextView

android - 在 Jetpack Compose 中使用 Horizo​​ntalPager + LazyVerticalGrid 时性能不佳

android - 如何异步调用rest api并等待所有调用在rx-android中完成

java - 为什么从 Java 代码访问对象类的 const 字段时出现错误

java - GoogleMap v2 Android 中的 Z 排序标记

Android View 在某些设备上的边框问题