https://kotlinlang.org logo
#announcements
Title
# announcements
g

groostav

02/23/2017, 11:47 PM
yeah @nkiesel, I think the suspected use case for
val 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
Copy code
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
n

nkiesel

02/24/2017, 12:27 AM
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
g

groostav

02/24/2017, 5:27 AM
yeah thats a very good point.
or perhalps
val name: String by map.safe()
, with
safe
being an extension method in the std:lib