I'd like to add/set elements of a mutable map with specific key-value pairs. So far, I figured out that I can can add new elements using the plus operator along with the Pair data type:
var arr3:Map<Any, Any> = mutableMapOf()
arr3 += Pair("manufacturer", "Weyland-Yutani")
//also, the "to" operator works too:
//arr3 += ("manufacturer" to "Weyland-Yutani")
However, I couldn't find out how to modify or add new key-value pairs:
arr3["manufacturer"] = "Seegson" // gives an error( Kotlin: No set method providing array access)
arr3["manufacturer"] to "Seegson" // compiles, but nothing is added to the array
Could you please elaborate me how to do that?
You've declared mutable arr3
with explicit type of Map<Any, Any>
. The Map
) interface allows no mutation. The +=
operator creates a new instance of map and mutates the variable arr3
. To modify contents of the map declare the arr3
as MutableMap
like so:
var arr3:MutableMap<Any, Any> = mutableMapOf()
or more idiomatic
var arr = mutableMapOf<Any, Any>()
Note that typically you need either mutable variable var
or mutable instance type MutableMap
but from my experience rarely both.
In other words you could use mutable variable with immutable type:
var arr = mapOf<Any,Any>()
and use +=
operator to modify where arr
points to.
Or you could use MutableMap
with immutable arr
variable and modify contents of where arr
points to:
val arr = mutableMapOf<Any,Any>()
Obviously you can only modify MutableMap
contents. So arr["manufacturer"] = "Seegson"
will only work with a variable which is declared as such.