I think that best way to emulate dot access to values of a map today is to write your custom property delegate like this:
class MutableProperty<T>: ReadWriteProperty<MutableMap<String, T>, T> {
override fun getValue(thisRef: MutableMap<String, T>, property: KProperty<*>): T = thisRef.getValue(property.name)
override fun setValue(thisRef: MutableMap<String, T>, property: KProperty<*>, value: T) {
thisRef[property.name] = value
}
}
Then declare properties that you need and use them anywhere in your code:
var MutableMap<String, String>.lastName by MutableProperty()
var MutableMap<String, Any>.anyProp by MutableProperty()
If you need the same property access on immutable map you should implement ReadOnlyProperty delegate too and declare same property for both map interfaces:
val Map<String, String>.lastName by ImmutableProperty()
var MutableMap<String, String>.lastName by MutableProperty()
@JvmName("get_MutableLastName") // this needed to resolve platform declaration clash
But I believe this approach adds some computation overhead to map access.
It would be great if Kotlin has a feature that would allow us to declare properties like this:
val Map<String, String>.firstName by this // also accessible on MutableMap as readonly property
var MutableMap<String, String>.lastName by this // also accessible on Map as readonly property
And this properties should be compiled to the same bytecode as simple map access in the place where it is used:
val firstName = myMap["firstName"]