Alexandru Gheorghe
04/26/2024, 1:22 PMMap<String, Map<String, Map<String, Int>>> and I'm trying to access it by nesting if statements. I am trying to increment the value (Int) to one provided as argument to a function.
In doing so, I'm encountering an issue: No set method providing array access when trying to do something like:
val keyMap = cls.parameter!!["key"] as Map<*, *>
// logic here to increment the value of the last key in the nested map
keyMap[nestedKey1][key] = new_value
the last statement is the one failing with the error shown above
my questions are:
1. how can I access nested maps in a safe manner and when I detect a key not existing, create it and nest in that if statement creating the rest of the map?
2. how can I set the map on an object (cls.parameter) such that I preserve other existing mappings and do not override with the new (and what would be the only if written) mapping?Ruckus
04/26/2024, 2:53 PMMap<String, Map<String, MutableMap<String, Int>>>Alexandru Gheorghe
04/26/2024, 3:05 PMMap< to `MutableMap<`and now I'm encountering the issue where I'm trying to access the key in order to set its value. E.g. map[key1][key2][key3] = value. In fact what I'm trying to do is Python equivalent of map[key1][key2][key3] += value. How can I achieve this value update for the innermost map and set it on a object while preserving the rest of the keys in the nested map?Ruckus
04/26/2024, 3:20 PMmap[key] will throw if the key isn't in the map, whereas in Kotlin it will just return null. You can work around this using other functions, but it won't be as pretty. Here's one example (not sure if there's a cleaner one):
map.getValue(key1).getValue(key2).let { it[key] = it.getOrDefault(key3, 0) + 1 }Alexandru Gheorghe
04/26/2024, 3:23 PMmap!![key1]?.get(key2) and I get an error on key2. Even though it's defined as a nested MutableMap.Ruckus
04/26/2024, 3:26 PMAlexandru Gheorghe
04/26/2024, 3:31 PMgetValue(key2) returns null? will the lambda create it? or do I have to deal with this case before calling the setting of the value?Ruckus
04/26/2024, 3:32 PMAlexandru Gheorghe
04/26/2024, 3:34 PMRuckus
04/26/2024, 3:40 PMRuckus
04/26/2024, 3:43 PMmap.getOrPut(key1) { mutableMapOf() }
.getOrPut(key2) { mutableMapOf() }
.let { it[key3] = it.getOrDefault(key3, 0) + 1 }Ruckus
04/26/2024, 3:46 PMwithDefault function, but that doesn't actually clean up the API at all, just eliminates the chance of throwing.
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/with-default.htmlAlexandru Gheorghe
04/26/2024, 3:47 PMKonstantin
04/26/2024, 8:28 PM