---
title: "How do you copy a map in Kotlin?"
description: "Copy a Kotlin map with toMap or toMutableMap. These make shallow copies, so nested mutable values are shared unless you copy them as well."
url: "https://bugsee.com/answers/kotlin/kotlin-copy-map/"
---

# How do you copy a map in Kotlin?

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.

```kotlin
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

- [How do you convert a Kotlin data class to JSON?](https://bugsee.com/answers/kotlin/kotlin-data-class-to-json/)
