Real estate delegation modified by volatile map

I have the following code:

class Mapped(var data:Map<String,String>){ val firstName:String by data } 

This works fine if Mapped used as follows:

 val mapped = Mapped(mapOf("firstName" to "initialFirstName")) println(mapped.firstName); // prints "initialFirstName" 

However, since the data property is mutable, we can change its value ie:

 mapped.data = mapOf("firstName" to "updated"); 

However, the firstName property still contains "initialFirstName" .

Is there any work with this known / documented , albeit unexpected (for me) behavior?

+6
source share
1 answer

As long as the problems of KT-5870 , KT-9772 are resolved, you can do the following:

 operator fun <V, V1 : V> (() -> Map<in String, V>).getValue(thisRef: Any?, property: KProperty<*>): V1 { val map = this() return map[property.name] as V1 } 

which can then be used as follows:

 class Mapped(var data:Map<String,String>){ val firstName:String by { data } } 

The above does not cope with a zero error. Here's an improved version:

 operator fun <V, V1 : V> (() -> Map<in String, V>).getValue(thisRef: Any?, property: KProperty<*>): V1 { val map = this() val key = property.name @Suppress("UNCHECKED_CAST") val value = map[key] as V1 if (property.returnType.isMarkedNullable) { return value } else { if(value != null){ return value } if(map.containsKey(key)){ throw KotlinNullPointerException("Property baking map returned null value for key '$key' for non nullable property: $property") } else { throw KotlinNullPointerException("Property baking map has no key '$key' for non nullable property $property") } } } 
+6
source

All Articles