How do you copy a map in Kotlin?

← Kotlin answers

Use map.toMap() for a read-only copy or map.toMutableMap() for an editable one. Both are shallow, so values that are themselves mutable are still shared.

val original = mapOf("a" to 1, "b" to 2)
 
val copy = original.toMap()                 // read-only copy
val editable = original.toMutableMap()      // changes do not affect original
editable["c"] = 3
 
val linked = LinkedHashMap(original)        // keeps insertion order
val hash = HashMap(original)
 
// Shallow copy problem
val nested = mapOf("tags" to mutableListOf("x"))
val shallow = nested.toMap()
shallow["tags"]!!.add("y")                  // nested["tags"] is now [x, y] too
 
// Copy the values as well
val deep = nested.mapValues { (_, v) -> v.toMutableList() }

mapOf returns a read-only view, not an immutable map: if another reference holds the underlying mutable map, you may still see changes. Copy defensively when you store a map you did not create.

Related questions

Start debugging smarter today

Try Bugsee for free — no commitments, no hidden fees.

Free sign upLive demoNo credit card required