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?
To add a new key-value pair to a mutable map, use put() . When a new entry is put into a LinkedHashMap (the default map implementation), it is added so that it comes last when iterating the map. In sorted maps, the positions of new elements are defined by the order of their keys.
To add a single element to a list or a set, use the add() function. The specified object is appended to the end of the collection. addAll() adds every element of the argument object to a list or a set.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With