I have a data class ``` data class Item( v...
# getting-started
f
I have a data class
Copy code
data class Item(
        val children: List<Item>
}
is there a way to make a deep (recursive) copy of such an object?
item.copy()
creates a copy of the top object only but not the
children
a
You can either create your own
copy
that does a deep copy or serialize and deserialize the whole instance
k
Do not abuse serialization for this.
Also if you're going to write a deep copy function think about whether these objects can ever be recursive.
p
still, imho
copy()
should be recursive
k
Definitely not, more often then not everything is immutable and then recursively copying would be a huge waste.
👍 2
p
it depends on the use case; you're right, in most current uses a deep copy would be a waste, but there are use cases in which it would be useful
when the object is the primary holder of one of its properties, a deep copy is what makes the most sense, and when they're just references to something handled somewhere else, just copying the reference is the way to go
f
can not imagine a real life case when I want to make a copy of a data object with the
copy
method but not including all inner data objects
k
When your data class references a bunch of immutable objects, and you want to make a copy with one of those references changed for example.
p
maybe a compiler hint telling when a field is the primary reference to its contents... so during copy() calls the fields annotated with that modifier are also copied, in a recursive call
...but that would be another big language proposal haha
a
"think about whether these objects can ever be recursive" -- I suspect that was specifically "think about whether there could be any cycles you have to deal with"
👍 1
k
It would be hard to justify compiler-generated code that throws overflowexceptions.