I need to make a built-in counter of the number of things through the Map in the Map.
initialization:
var Items = mapOf<Map<String, Item>, Int>()
Example of interaction
for(i in item)
if (this.UnitInventory.Items.containsKey(Pair(i.Name, i) as Map<String, Item>))
this.UnitInventory.Items[Pair(i.Name, i)]
else
this.UnitInventory.Items = mapOf(Pair(Pair(i.Name, i) as Map<String, Item>, 1))
How to properly write part this.UnitInventory.Items[Pair(i.Name, i)]
?
CodePudding user response:
Like Tenfour04 says in the comments, this is kinda brittle - but so long as you're using immutable Map
s as keys it's probably ok? Anyway, if that's what you want, you can do this:
// this -outer- map needs to be mutable (since you'll be adding new counts)
val items = mutableMapOf<Map<String, Int>, Int>()
// make some map keys to count
val someMap = mapOf("One" to 1)
val someOtherMap = mapOf("Two" to 2, "Three" to 3)
val stuff = listOf(someMap, someOtherMap, someMap)
// add them to the counts
stuff.forEach { item ->
// update the current count, defaulting to zero if it doesn't exist yet
items[item] = items.getOrDefault(item, 0) 1
}
println(items)
>> {{One=1}=2, {Two=2, Three=3}=1}