https://kotlinlang.org logo
Title
a

Andrea Giuliano

10/13/2020, 4:10 PM
Hi guys, given I have a map like
val myMap = sortedMapOf<String, Collection<Int>>()
Is there a way to put into the map and overflow in the collection in case the key already exist in the map?
d

diesieben07

10/13/2020, 4:10 PM
myMap.getOrPut(key) { MyCollection() } += myValue
a

Andrea Giuliano

10/13/2020, 4:12 PM
thanks!
n

nanodeath

10/13/2020, 4:23 PM
to perhaps state the obvious, make sure it's a mutable collection :)
👍 1
a

Andrea Giuliano

10/13/2020, 4:26 PM
only thing is, it seems I can’t really do
myMap.getOrPut(key) { MyCollection() } += myValue
kotlin expects that I put the list in a val before doing +=
d

diesieben07

10/13/2020, 4:30 PM
Make sure both your map and your collection are mutable. In my test it works fine: https://pl.kotl.in/psAZfS9uZ
a

Andrea Giuliano

10/13/2020, 4:30 PM
yeah I can use .add() but not += for some reasons, but that’s fine 🙂