Does copy() in data class works the same like clon...
# announcements
j
Does copy() in data class works the same like clone() in Java Object? Do copied object shares the same HashCode? And - how interface Cloneable is working in Kotlin if Any do not have protected clone() method?
i
Copy creates copy of the object with the same hashcode. You cam additionally modify some properties
Copy code
val cp = a.copy(weight = 12) //this of course will change hash code
I am not sure how this refers to
Cloneable
however I know that this is not a deep copy (so if there is an object in data class only reference will be copied to new data class, so original and copy would have reference the same object stored internally)
r
Depends how you create HashCode from your object. I would create a test to check that all your needed cases are taken care of
i
FYI hash code of data class is generated only from the properties defined in primary constructor
s
Indeed, and the same is true for
copy()
, it operates on the primary constructor properties only.
Essentially, that's the case for all the stuff that's generated for you with data classes.
equals
,
hashCode
,
componentX
, everything.
b
Is this a form of structural sharing so copy will maintain any internal references unless you change them in the copied instance, something akin to a persistent data structure?
p
No, it's just a copy constructor where you also change values.
Google "Java copy constructor"