Reputation: 4415
So I have the following data class:
data class Client(val name: String, val pastAddresses: ArrayList<String>)
From the following code:
val aClient = Client("Alice", arrayListOf("foo", "bar"))
println(aClient)
val cClient = aClient.copy()
cClient.pastAddresses.add("Blah")
cClient.pastAddresses.remove("foo")
println(aClient)
I see:
Client(name=Alice, pastAddresses=[foo, bar])
Client(name=Alice, pastAddresses=[bar, Blah])
Which means that the copy in Kotlin's data class is a shallow copy.
Is there a way to do a deep copy?
Upvotes: 2
Views: 1836
Reputation: 5207
You are right. The default copy()
method creates a shallow copy.
Look at the Kotlin documentation:
It's often the case that we need to copy an object altering some of its properties, but keeping the rest unchanged. This is what copy() function is generated for.
You can override it so that it does what you need. But I'd suggest you to create a new method that creates a deep copy, let name it deepCopy()
. Why is it better? Because if your application grows, there still can be cases when you need a shallow copy. That's why having 2 different methods can help to clearly distinguish it.
Upvotes: 6