31
votes

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?

Edit: this is the compile error

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
Why do you think it is not possible? It should work the same. Please explain what problems you have with the second code snippet. - voddan
It doesn't compile, updated with compiler error. - Francesc

1 Answers

70
votes

For some reason the type inference fails here. You have to specify the type of the delegate manually. Instead you can omit the property type declaration:

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

Please file an issue at https://youtrack.jetbrains.com/issues/KT