Reputation: 4371
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.
Upvotes: 2
Views: 16569
Reputation: 58772
You can't add to your map because mapOf
is creating a read-only map
fun <K, V> mapOf(): Map<K, V>
Returns an empty read-only map.
You probably want to create a MutableMap (or similar)
private var optionsList: Map<String, List<String>> = mutableMapOf()
You can then use plus method:
optionsList = optionsList.plus("list_1" to theSteps)
Or see other options as @voddan:
val nameTable = mutableMapOf<String, Person>() fun main (args: Array<String>) { nameTable["person1"] = example
Upvotes: 2
Reputation: 170723
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)
Upvotes: 4