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") } } }
source share