data class Person(val name: String, var age: Int) ...
# announcements
m
data class Person(val name: String, var age: Int) fun main() { val person1 = Person("Murali", 21) val person2 = person1.copy() } Now my question is do the fields in both person1 and person2 refer to the same objects? I mean person1.age === person2.age ?
h
in the future, please use code snippets, or atleast add your code between\ 3 back ticks
m
Thanks!
h
and no, they don’t
m
Typing from phone!
h
then you can click the + and add a “code snippet” 🙂
m
Was not familiar with that feature
But the boolean expression gives true
h
hmm, i must be wrong then. it should make sense they are not the same
i’ll let someone else explain
k
You happened to choose two of the worst types to test this with,
String
and
Int
are both special cases.
But yes, they always will point to the same objects.
copy
isn't magically a deep copy, it only copies the object itself, not the contents of the fields.
m
But i did test with different types but this seems no different than clone().
Thanks @karelpeeters!
g
@karelpeeters @muralimohan962 Actually, copy makes in fact deep copy, see https://kotlinlang.org/docs/reference/data-classes.html#copying As for referential equality
Copy code
person1.age === person2.age
is True, but that doesn't mean that variables point to same object, it gets translated to
Copy code
==
for value types, see https://kotlinlang.org/docs/reference/equality.html#referential-equality
k
Nope it does definitely not make a deep copy.
===
and
==
are indeed the same for primitives, but that's not really relevant here.
g
Ok, my points is, copy does not return same object, it creates new one
k
Yes, it creates a shallow copy.
👍 4