Francesc
Francesc

Reputation: 29260

Kotlin: nullable property delegate observable

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

Upvotes: 31

Views: 6907

Answers (1)

voddan
voddan

Reputation: 33769

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

Upvotes: 70

Related Questions