Copying and cloning

suggest change

Kotlin has no single "clone this object" operation. Instead you pick the right tool for the kind of value:

Almost all of these make a shallow copy: the outer object is new, but the objects it refers to are shared. Knowing where a copy stops being a copy is most of what this article is about.

Assignment copies the reference

Assigning an object to another variable doesn't copy it. Both variables point to the same object:

fun main() {
    val a = mutableListOf(1, 2, 3)
    val b = a          // copies the reference, not the list
    b.add(4)
    println(a)         // the change is visible through a
    println(a === b)
}
[1, 2, 3, 4]
true

The same is true when you pass an object to a function or store it in a property. See Values and references for the details of == vs === and pass-by-value semantics.

Immutable values such as String, Int and other numbers, LocalDate or a List created with listOf never need to be copied: since nobody can change them, sharing is safe.

Copying data classes with copy()

The compiler generates a copy() function for every data class. Each primary constructor property becomes a parameter with the current value as its default, so you name only what you want to change:

data class User(val name: String, val email: String, val age: Int)

fun main() {
    val alice = User("Alice", "alice@example.com", 30)
    val older = alice.copy(age = 31)
    val renamed = alice.copy(name = "Alicia", email = "alicia@example.com")

    println(alice)
    println(older)
    println(renamed)
    println(alice == alice.copy())   // same content
    println(alice === alice.copy())  // but a new object
}
User(name=Alice, email=alice@example.com, age=30)
User(name=Alice, email=alice@example.com, age=31)
User(name=Alicia, email=alicia@example.com, age=30)
true
false

This is the idiomatic way to "modify" immutable objects in Kotlin: keep all properties val and produce updated versions with copy().

copy() is shallow

copy() passes the existing property values to the constructor. For a property that holds a mutable object, the new instance gets the same reference:

data class Team(val name: String, val members: MutableList<String>)

fun main() {
    val original = Team("core", mutableListOf("Ann", "Bob"))
    val copy = original.copy(name = "core-2")

    copy.members.add("Eve")

    println(original)
    println(copy)
    println(original.members === copy.members)
}
Team(name=core, members=[Ann, Bob, Eve])
Team(name=core-2, members=[Ann, Bob, Eve])
true

Adding Eve to the copy also changed the original, because both share one list.

The best fix is to avoid mutable state inside data classes. With a read-only List, you "add" by creating a new list and passing it to copy():

data class Team(val name: String, val members: List<String>)

fun main() {
    val team = Team("core", listOf("Ann", "Bob"))
    val bigger = team.copy(members = team.members + "Eve")

    println(team)
    println(bigger)
}
Team(name=core, members=[Ann, Bob])
Team(name=core, members=[Ann, Bob, Eve])

Writing a deep copy by hand

When mutable members can't be avoided, write a deep copy that copies each mutable part explicitly:

data class Address(var city: String)
data class Person(val name: String, val address: Address, val tags: MutableList<String>)

fun Person.deepCopy(): Person = copy(
    address = address.copy(),
    tags = tags.toMutableList(),
)

fun main() {
    val p1 = Person("Ann", Address("Paris"), mutableListOf("admin"))
    val p2 = p1.deepCopy()

    p2.address.city = "Berlin"
    p2.tags.add("editor")

    println(p1)
    println(p2)
}
Person(name=Ann, address=Address(city=Paris), tags=[admin])
Person(name=Ann, address=Address(city=Berlin), tags=[admin, editor])

A hand-written deep copy is verbose, but it's fast and type-safe, and it shows exactly what gets duplicated.

Properties in the class body are not copied

copy(), like equals(), hashCode() and toString(), only uses properties declared in the primary constructor. A property declared in the class body gets its initial value in the copy:

data class Counter(val name: String) {
    var hits: Int = 0   // declared in the body, not in the constructor
}

fun main() {
    val c = Counter("home")
    c.hits = 42
    val d = c.copy()

    println("c.hits=${c.hits} d.hits=${d.hits}")
    println(c == d)   // equals() ignores body properties too
}
c.hits=42 d.hits=0
true

If a value must survive copy(), put it in the primary constructor.

copy() and private constructors

A common pattern is a data class with a private constructor and a factory function that validates or normalizes input. The catch: historically copy() was always public, so anyone could call copy() and skip the validation.

Kotlin 2.x is fixing this. The compiler warns about such classes, and in language version 2.5 the warning becomes an error. Opt in to the new behavior now with @ConsistentCopyVisibility, which gives copy() the same visibility as the constructor:

@ConsistentCopyVisibility
data class Email private constructor(val value: String) {
    companion object {
        fun of(raw: String): Email {
            require("@" in raw) { "invalid email: $raw" }
            return Email(raw.trim().lowercase())
        }
    }
}

fun main() {
    val e = Email.of("  Ann@Example.com ")
    println(e)
    // e.copy(value = "not an email")
    // error: cannot access 'fun copy(value: String = ...): Email': it is private in 'Email'.
}
Email(value=ann@example.com)

You can also turn it on for the whole module with the -Xconsistent-data-class-copy-visibility compiler flag.

Copying collections

Every toXxx() conversion function on collections creates a new collection with the same elements:

fun main() {
    val source = mutableListOf("a", "b", "c")

    val list: List<String> = source.toList()
    val mutable: MutableList<String> = source.toMutableList()
    val set: Set<String> = source.toSet()
    val alsoList = ArrayList(source)   // Java-style copy constructor

    source.add("d")

    println("source   = $source")
    println("list     = $list")
    println("mutable  = $mutable")
    println("set      = $set")
    println("alsoList = $alsoList")
}
source   = [a, b, c, d]
list     = [a, b, c]
mutable  = [a, b, c]
set      = [a, b, c]
alsoList = [a, b, c]

Use toList() when you want a snapshot nobody can change, and toMutableList() when you want your own list to modify.

A read-only view is not a copy

Assigning a MutableList to a variable of type List doesn't copy anything. List only hides the mutating methods; the underlying object is still the same mutable list:

fun main() {
    val source = mutableListOf(1, 2, 3)
    val readOnly: List<Int> = source   // a read-only view, not a copy

    source.add(4)
    println(readOnly)

    // the view can even be cast back and mutated
    (readOnly as MutableList<Int>).add(5)
    println(source)
}
[1, 2, 3, 4]
[1, 2, 3, 4, 5]

If a value must not change, copy it with toList(), or use truly immutable collections from the kotlinx-collections-immutable library (persistentListOf, toPersistentList()).

Maps and the + / - operators

Maps work the same way. The + and - operators also return new collections and leave the original alone:

fun main() {
    val prices = mutableMapOf("apple" to 3, "pear" to 4)

    val snapshot: Map<String, Int> = prices.toMap()
    val editable: MutableMap<String, Int> = prices.toMutableMap()
    val withPlum = prices + ("plum" to 5)       // new map
    val withoutPear = prices - "pear"           // new map

    prices["apple"] = 10
    editable["kiwi"] = 2

    println("prices      = $prices")
    println("snapshot    = $snapshot")
    println("editable    = $editable")
    println("withPlum    = $withPlum")
    println("withoutPear = $withoutPear")
}
prices      = {apple=10, pear=4}
snapshot    = {apple=3, pear=4}
editable    = {apple=3, pear=4, kiwi=2}
withPlum    = {apple=3, pear=4, plum=5}
withoutPear = {apple=3}

Nested collections need a deep copy

Collection copies are shallow too: the new list holds the same element objects. For a list of mutable lists, copy each inner list with map:

fun main() {
    val grid = mutableListOf(
        mutableListOf(1, 2),
        mutableListOf(3, 4),
    )

    val shallow = grid.toMutableList()
    val deep = grid.map { it.toMutableList() }

    grid[0][0] = 99

    println("grid    = $grid")
    println("shallow = $shallow")
    println("deep    = $deep")
}
grid    = [[99, 2], [3, 4]]
shallow = [[99, 2], [3, 4]]
deep    = [[1, 2], [3, 4]]

The same applies to a list of data classes with mutable properties: people.map { it.copy() } (or your own deepCopy()) copies the elements, people.toList() doesn't.

Copying arrays

Arrays have several copy functions. All of them return a new array:

fun main() {
    val nums = intArrayOf(1, 2, 3, 4, 5)

    val all = nums.copyOf()
    val longer = nums.copyOf(7)          // padded with zeros
    val shorter = nums.copyOf(3)         // truncated
    val middle = nums.copyOfRange(1, 4)  // indexes 1, 2, 3
    val cloned = nums.clone()

    nums[0] = 100

    println(nums.contentToString())
    println(all.contentToString())
    println(longer.contentToString())
    println(shorter.contentToString())
    println(middle.contentToString())
    println(cloned.contentToString())
}
[100, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5, 0, 0]
[1, 2, 3]
[2, 3, 4]
[1, 2, 3, 4, 5]

clone() exists only on the JVM. Prefer copyOf(), which also works in multiplatform code.

For an Array<T>, growing with copyOf(newSize) returns Array<T?>, because the new slots are filled with null. To copy into an existing array use copyInto:

fun main() {
    val names = arrayOf("Ann", "Bob")
    val padded: Array<String?> = names.copyOf(4)   // new slots are null
    println(padded.contentToString())

    val src = intArrayOf(1, 2, 3)
    val dst = IntArray(6)
    src.copyInto(dst, destinationOffset = 2)
    println(dst.contentToString())

    val list = src.toList()          // array -> list copy
    val back = list.toIntArray()     // list -> array copy
    println("$list ${back.contentToString()}")
}
[Ann, Bob, null, null]
[0, 0, 1, 2, 3, 0]
[1, 2, 3] [1, 2, 3]

A two-dimensional array is an array of arrays, so copyOf() copies only the outer array. Copy each row for a deep copy:

fun main() {
    val matrix = arrayOf(intArrayOf(1, 2), intArrayOf(3, 4))

    val shallow = matrix.copyOf()
    val deep = Array(matrix.size) { matrix[it].copyOf() }

    matrix[0][0] = 99

    println(shallow.contentDeepToString())
    println(deep.contentDeepToString())
}
[[99, 2], [3, 4]]
[[1, 2], [3, 4]]

Copying regular classes

Copy constructors

For a class that isn't a data class, a secondary constructor that takes another instance is the clearest option:

class Document(val title: String, lines: List<String>) {
    private val lines: MutableList<String> = lines.toMutableList()

    // copy constructor
    constructor(other: Document) : this(other.title, other.lines)

    fun append(line: String) { lines += line }
    override fun toString() = "$title: $lines"
}

fun main() {
    val draft = Document("notes", listOf("first"))
    val copy = Document(draft)
    copy.append("second")

    println(draft)
    println(copy)
}
notes: [first]
notes: [first, second]

The primary constructor already copies the incoming list with toMutableList(), so the copy gets its own list for free.

Cloneable and clone()

Kotlin supports the Java cloning mechanism. Implement Cloneable, then override clone() and make it public (Kotlin's Cloneable declares it as protected). super.clone() makes a field-by-field shallow copy, and you have to deep-copy the mutable fields yourself:

class Point(var x: Int, var y: Int) : Cloneable {
    public override fun clone(): Point = super.clone() as Point
    override fun toString() = "Point($x, $y)"
}

class Polygon(val name: String, var points: MutableList<Point>) : Cloneable {
    public override fun clone(): Polygon {
        val copy = super.clone() as Polygon    // field-by-field shallow copy
        copy.points = points.mapTo(mutableListOf()) { it.clone() }
        return copy
    }
    override fun toString() = "Polygon($name, $points)"
}

fun main() {
    val a = Polygon("tri", mutableListOf(Point(0, 0), Point(1, 0), Point(0, 1)))
    val b = a.clone()
    b.points[0].x = 5
    b.points.add(Point(9, 9))

    println(a)
    println(b)
}
Polygon(tri, [Point(0, 0), Point(1, 0), Point(0, 1)])
Polygon(tri, [Point(5, 0), Point(1, 0), Point(0, 1), Point(9, 9)])

Notice that points had to become a var so clone() could replace it. clone() bypasses constructors, needs casts, and throws CloneNotSupportedException if you forget Cloneable. Use it only for Java interop; copy() or a copy constructor is better in Kotlin code.

Defensive copies

A class that stores a collection passed in from outside, or returns its internal collection, should copy it. Otherwise the caller and the class silently share state:

class Playlist(songs: List<String>) {
    // copy on the way in: later changes to the caller's list don't leak in
    private val songs = songs.toMutableList()

    fun add(song: String) { songs += song }

    // copy on the way out: callers can't change our state through the result
    fun songs(): List<String> = songs.toList()
}

fun main() {
    val input = mutableListOf("Intro", "Theme")
    val playlist = Playlist(input)
    input.clear()

    val snapshot = playlist.songs()
    playlist.add("Outro")

    println(input)
    println(snapshot)
    println(playlist.songs())
}
[]
[Intro, Theme]
[Intro, Theme, Outro]

Remember that a parameter typed List<String> may still be a MutableList that the caller keeps changing. Copying on the way out is especially important when other threads read the result.

Generic deep copy with serialization

For a large object graph, writing deep copies by hand gets tedious. One generic trick is to serialize the object and read it back. With Java serialization this needs no extra libraries:

import java.io.*

data class Node(val name: String, val children: MutableList<Node> = mutableListOf()) : Serializable

@Suppress("UNCHECKED_CAST")
fun <T : Serializable> T.deepCopy(): T {
    val bytes = ByteArrayOutputStream().also { out ->
        ObjectOutputStream(out).use { it.writeObject(this) }
    }.toByteArray()
    return ObjectInputStream(ByteArrayInputStream(bytes)).use { it.readObject() as T }
}

fun main() {
    val root = Node("root", mutableListOf(Node("a"), Node("b")))
    val copy = root.deepCopy()

    copy.children[0].children.add(Node("a1"))

    println(root)
    println(copy)
    println(root.children[0] === copy.children[0])
}
Node(name=root, children=[Node(name=a, children=[]), Node(name=b, children=[])])
Node(name=root, children=[Node(name=a, children=[Node(name=a1, children=[])]), Node(name=b, children=[])])
false

Every class in the graph must implement Serializable, and the round trip is much slower than a hand-written copy. A JSON round trip with kotlinx.serialization (Json.decodeFromString<T>(Json.encodeToString(value))) works the same way for @Serializable classes. See Serializable and serialVersionUid in Kotlin for more on Serializable.

Summary

What Shallow copy Deep copy
data class x.copy() copy() with copied mutable properties
List / Set toList(), toMutableList(), toSet() map { it.copy() }, map { it.toMutableList() }
Map toMap(), toMutableMap() mapValues { it.value.copy() }
array copyOf(), copyOfRange() Array(n) { a[it].copyOf() }
regular class copy constructor, clone() copy each mutable field

Best practices:

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents