nkiesel
02/24/2017, 12:27 AMval x by map
was that it would primarily operate on objects of disparate types (a le Javascript), thus I think the by map
idea was largely aimed as a shim for dynamic languages into kotlin.
But I could agree with your assestment, especially when we have access to raw types. Perhaps it would be better if we had something like
val map: Map<String, Any?> = ...
val name:String by map //compiler error: cannot use `Map<String, Any?> as delegate for `val name: String` expected Value type to be String but was Any?
val name: String by (map as Map) //compiler warning: unchecked raw type cast: Map<String, Any?> to Map
val name: String by @SuppressWarnings("unchecked")(map as Map) //compiles without issue
unfortunately its a moot point since any change would break backwards compatibility in a pretty big way
Slack Conversation
groostav: The following might be a better way than using a plain Map:
class Safe<V>(val map: Map<String, V>) {
operator fun getValue(t: Any?, k: KProperty<*>): V = map.get(k.name) ?: throw Exception()
}
class User(val map: Map<String, String>) {
val name: String by Safe(map)
}
This at least now complaints if the property type and the map value type mismatch