Reputation: 3074
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?
Upvotes: 31
Views: 28596
Reputation: 147911
Regarding the add/set operations, these can be performed on the MutableMap<K, V>
(not just Map<K, V>
) and can be done in several ways:
The Java-style put
call:
arr3.put("manufacturer", "Seegson")
This call returns the value that was previously associated with the key, or null
.
A more idiomatic Kotlin call using the set
operator:
arr["matufacturer"] = "Seegson"
The plusAssign
operator syntax:
arr += "manufacturer" to "Seegson"
This option introduces overhead of a Pair
created before the call and is less readable because it can be confused with a var
reassignment (also, it is not applicable for var
s because of ambiguity), but still is useful when you already have a Pair
that you want to add.
Upvotes: 20
Reputation: 41608
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.
Upvotes: 40