Search code examples
arrayskotlinhashmapmutablelist

How add a list inside a map in kotlin


I need to add some MutableList<String> to a map Map<String, List<String>>, here is how I tried to initialize it :

    private var theSteps: MutableList<String> = mutableListOf()
    private var optionsList: Map<String, List<String>> = mapOf()

Then I add data to the `MutableList this way :

        theSteps.add("one")
        theSteps.add("two")
        theSteps.add("three")

everything works fine untill i try to add to the Map:

optionsList.add("list_1" to theSteps)

It just gives me the error Unresolved reference add and I can't find clear documentation about how to add items to it.


Solution

  • optionsList must be a MutableMap to add anything, just like you have a MutableList; or you can use

    theSteps += "list_1" to theSteps
    

    to create a new map with the added pair and update theSteps variable. This calls the plus extension function:

    Creates a new read-only map by replacing or adding an entry to this map from a given key-value pair.

    (search for the above to get to the correct overload)