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
