Matt
03/15/2019, 2:42 PMval myMap = mutableMapOf<String, List<String>>()
and try to add:
myMap["a"] = listOf("1")
myMap["a"] = listOf("2")
I'd like to have:
"a"=["1","2"]
How can I achieve this? Can I achieve it using an immutable map?Dico
03/15/2019, 2:45 PMval myMap = mutableMapOf<String, MutableList<String>>().withDefault { mutableListOf() }
myMap["a"]!! += "1"
myMap["a"]!! += listOf("2")Matt
03/15/2019, 2:56 PMmyMap["a"]!! += "1"Dico
03/15/2019, 2:57 PM.getValue("a) 😞Dico
03/15/2019, 2:57 PMMatt
03/15/2019, 2:57 PMDico
03/15/2019, 2:57 PMMike
03/15/2019, 3:01 PMkotlin
val map = mutableMapOf<String, MutableList<String>>()
map.getOrPut("a") {mutableListOf()}.add("1")
map.getOrPut("a") {mutableListOf()}.add("2")
map.getOrPut("b") {mutableListOf()}.add("3")
map //{a = [1,2], b [3]}Mike
03/15/2019, 3:02 PMMatt
03/15/2019, 3:20 PMDico
03/15/2019, 3:21 PMwithDefaultDico
03/15/2019, 3:29 PMDico
03/15/2019, 3:30 PMMike
03/15/2019, 3:36 PMwithDefault existed on map, so thank you for that.
The big difference is my approach only allows adding elements, so if adding/merging a List is a requirement, it doesn’t help.
I guess the other difference is getOrPut knows that map is not null whereas it appears using withDefault doesn’t provide enough information to the compiler so it can know the result of the get won’t be null.Mike
03/15/2019, 3:37 PMMike
03/15/2019, 3:49 PMwithDefault requires also using getValue, so then compiler knows it’s not null BUT doing a getValue returns the default, BUT doesn’t add an entry into the map for the missing key.
kotlin
val map2 = mutableMapOf<String, MutableList<String>>().withDefault { mutableListOf() }
val value = map2.getValue("a")
value += "1"
val value2 = map2.getValue("a")
value2 += "2"
map2.getValue("b").add("2")
map2
And map 2 is empty, as is value2 after the getValue.