Search code examples
kotlinclone

How to clone object in Kotlin?


The Kotlin documentation describes cloning only in accessing Java and in enum class. In latter case clone is just throwing an exception.

So, how would I / should I clone arbitrary Kotlin object?

Should I just use clone() as in Java?


Solution

  • For a data class, you can use the compiler-generated copy() method. Note that it will perform a shallow copy.

    To create a copy of a collection, use the toList() or toSet() methods, depending on the collection type you need. These methods always create a new copy of a collection; they also perform a shallow copy.

    For other classes, there is no Kotlin-specific cloning solution. You can use .clone() if it suits your requirements, or build a different solution if it doesn't.