Kotlin basics: how to add or set an element of a Map? Kotlin basics: how to add or set an element of a Map? arrays arrays

Kotlin basics: how to add or set an element of a Map?


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 vars because of ambiguity), but still is useful when you already have a Pair that you want to add.