Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin: nullable property delegate observable

Tags:

android

kotlin

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 
like image 864
Francesc Avatar asked Jan 08 '17 18:01

Francesc


1 Answers

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

like image 67
voddan Avatar answered Sep 25 '22 13:09

voddan