How to modify inner list?


#1

var listOfLists : List<List<Int>> = mutableListOf()

If I want to add some elements to the inner list, what should I do? The inner list seems to be immutable be default.

Same thing happens with Map. In Java, I can do this:
Map<String, List<String>> map = ......
map.computeIfAbsent(key, key -> new ArrayList<>()).add("a string").

How can I achieve the same with Kotlin?


#2

In Kotlin if you just do List it’s immutable. If you want to modify the content you must write the Mutable prefix. So, for List it’ll be MutableList and for Map it’ll be MutableMap


#3

I understand that. It’s the inner list. I don’t know how to make it mutable.


#4

Just write List<MutableList<Int>> if you want only the inner list to be mutable. Otherwise, do MutableList<MutableList<Int>>


#5

You are right!! Thanks a lot.