The question is that simple.
Kotlin documentation describes cloning only in accessing Java and in enum class. In latter case clone is just throwing an exception.
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.
Here is a consistent solution that works for any object type:
Kotlin's Array data structure provides a clone() method that can be used to clone the contents of the array:
val a = arrayOf(1)
//Prints one object reference
println(a)
//Prints a different object reference
println(a.clone())
As of Kotlin 1.3, the clone method has been supported on all major targets, so it should be usable across platforms.
A Kotlin data class
is easy to clone using .copy()
All values with be shallow copied, be sure to handle any list/array contents carefully.
A useful feature of .copy()
is the ability to change any of the values at copy time. With this class:
data class MyData(
val count: Int,
val peanuts: Int?,
val name: String
)
val data = MyData(1, null, "Monkey")
You could set values for any of the properties
val copy = data.copy(peanuts = 100, name = "Elephant")
The result in copy
would have values (1, 100, "Elephant")