liveBook · Manning

MutableMap

As explained in Kotlin in Action, 2E

MutableMap is a Kotlin collection interface representing key-value associations that can be modified.

MutableMap is Kotlin’s modifiable key-value collection interface. Kotlin separates it from the read-only Map interface while retaining direct interoperability with Java collections. section 8.2.3

Store dynamic properties in a MutableMap

class Person { private val attributes = mutableMapOf<String, String>() fun setAttribute(name: String, value: String) { attributes[name] = value } var name: String by attributes } val person = Person() person.setAttribute("name", "Seb") println(person.name) // Seb person.name = "Sebastian" println(person.name) // Sebastian The delegated property uses the property name as the map key. Kotlin’s standard library supplies getValue and setValue for Map and MutableMap. section 9.5.5

Create and use mutable maps with Kotlin’s collection functions.

  • Use mutableMapOf, hashMapOf, linkedMapOf, sortedMapOf, or buildMap to obtain mutable-map implementations or builders. section 8.2.3
  • Treat a MutableMap as mutable even when passing collections across Kotlin and Java; Java code can modify collections declared read-only on the Kotlin side. section 8.2.3
Listing 9.25 Defining a property that stores its value in a map
class Person {
    private val _attributes = mutableMapOf<String, String>()
 
    fun setAttribute(attrName: String, value: String) {
        _attributes[attrName] = value
    }
 
    var name: String
        get() = _attributes["name"]!!     #1
        set(value) {
            _attributes["name"] = value   #2
        }
}
 
fun main() {
    val p = Person()
    val data = mapOf("name" to "Seb", "company" to "JetBrains")
    for ((attrName, value) in data)
       p.setAttribute(attrName, value)
    println(p.name)
    // Seb
    p.name = "Sebastian"
    println(p.name)
    // Sebastian
}

Follow a complete map-backed property example with explicit getters, setters, attribute loading, and mutation. section 9.5.5

How Kotlin in Action, 2E covers it

How deep it goes
Explains interface separation, creation functions, Java mutation risks, and delegated-property mechanics.
Examples
Demonstrates mutable-map factory functions, Java collection mutation, and Person attributes stored through explicit or delegated properties.
What it assumes
Assumes basic Kotlin collections and properties while distinguishing read-only from mutable interfaces.
What you can do after
Apply it via Kotlin map factories, indexed updates, and delegated properties for dynamic attributes.
How it connects
Connects MutableMap with Map, Kotlin collection interfaces, Java collections, delegated properties, and property accessors.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Kotlin in Action, 2E. The section links point to the parts of the book it draws on.