Hi, I have a map<string, any>, and I was won...
# announcements
n
Hi, I have a map<string, any>, and I was wondering is there a way to access the values of the map As if they where variable names. Same way a with will work on an object.   Something like:
map = mapOf("one" to 1, "two" to "2")
magicWith(map) {
one // 1
two // "2"
}
(I don’t want to create a data class to reduce boilerplates)
l
that kind of magic doesn't exist AFAIK
But IMO doing that would be more boilerplate than using a data class
It's a single line that makes it explicit what you're doing
Passing maps around is bad as they're not explicit. "Oh, what's the key that I needed here? Let me check"
"Was it one or ONE?"
"Was it an int or a long?"
However, with a single
data class MyData(val one: Int, val two: String)
would make things explicit in whichever flow you're using
m
Closest you can get is writing a
Delegate
and then use it like this:
Copy code
magicWith(map) {
   val one by name
   val two by name
}
Or just:
Copy code
val one by map
val two by map
☝🏼 1
Not sure if the second case is possible tbh 😄 It is!
l
I think the closest you can get is something like
Copy code
magicWith(map) {
   it["one"] // 1
   it["two"] // 2
}
But that's using default
get
Creating a property from a name in the map is impossible
m
It works 🙂
Copy code
val map = mapOf("one" to 1, "two" to "2")

val one by map  // Any?
val two by map  // Any?



operator fun <Value> Map<String, Value>.getValue(thisRef: Any?, property: KProperty<*>) =
    this[property.name]
l
Ah, a value works, yes
I thought that they wanted a property like using a map as if it was a data class
m
Well mine is not exactly what Nir has asked for, but close. You’re right that map keys won’t magically become variable names 🙂
In Kotlin/JS this may even work:
Copy code
with(map.asDynamic()) {
   one
   two
}
I have no idea how Kotlin/JS handles a
dynamic
this
.
n
Thanks @LeoColman and @Marc Knaup for your answers!