In Kotlin we can define an observable for a non-null property,

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

however this is not possible

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

What would be the way to define an observable for a nullable property?

编辑:这是编译错误

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

推荐答案

由于某些原因,类型推理在这里失败.您必须手动指定委派的类型.相反,您可以省略属性类型声明:

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

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

Kotlin相关问答推荐

&x是T&q;和&q;(x为?T)!=空(&Q;)?

如何在 Spring Boot 3 中为内部类提供运行时提示

Kotlin:我可以将函数分配给 main 的伴随对象中的变量吗?

循环中的每个元素都应填充行中可用的所有可用空间

如何在 Kotlin for Android 上使用setTextColor(hexaValue),

错误:cannot find symbol import com.gourav.news.databinding.ActivityDetailBindingImpl;

如何使用 Kotlin KClass 属性 simpleName 生成空值

如何在 IntelliJ 中更改 Kotlin 的this property has a backing field代码编辑器突出显示?

Kotlin - 当表达式返回函数类型

在 Scaffold Jetpack Compose 内的特定屏幕上隐藏顶部和底部导航器

如何设置两列recyclerview?

Dagger2 Qualifier 不适用于 Kotlin?

如何在Kotlin中创建填充空值的通用数组?

Kotlin 扩展函数 - 覆盖现有方法

如何将map函数应用于Kotlin中的数组并更改其值?

ObserveForver是否了解生命周期?

如何在 Jetpack Compose 的 LazyColumn/LazyRow 中禁用和启用滚动?

类型不匹配:推断类型为 LoginActivity 但应为 LifecycleOwner

在 kotlin 中,如何将主构造函数中的属性设置器设为私有?

用 kotlin 学习 Android MVVM 架构组件