Maybe I'm misinterpreting how the copy
function of a data
class works or maybe there's a bug, but the following is an example of the copy
function not working as expected:
Kotlin:
data class A {
public var x: String? = null
public var y: String? = null
public var z: B = B.ONE
}
enum class B {
ONE
TWO
THREE
}
Java
A a1 = new A()
a1.setX("Hello")
a1.setY("World")
a1.setZ(B.TWO)
A a2 = a1.copy()
// a2.x is null
// a2.y is null
// a2.z is B.ONE
It seems that copy
is just making a new instance of A
and not copying the values. If I put the variables in the constructor, the values are assigned, but then it's no different than constructing a new instance.
As a quick refresher, Kotlin is a modern, statically typed language that compiles down for use on the JVM. It's often used wherever you'd reach for Java, including Android apps and backend servers (using Java Spring or Kotlin's own Ktor).
Kotlin generates the basic functions that must be overloaded for a good model class, giving us good toString(), hashCode(), and equals() functions. Kotlin also provides some extra functionality in the form of a copy() function, and various componentN() functions, which are important for variable destructuring.
Kotlin makes working with immutable data objects easier by automatically generating a copy() function for all the data classes. You can use the copy() function to copy an existing object into a new object and modify some of the properties while keeping the existing object unchanged.
The copy() function is not a deep copy or a clone function. It makes a shallow copy of class. It is used in the case where we need to copy an object altering some of its properties, but keeping the rest unchanged.
Okay, I missed this sentence in the docs:
If any of these functions is explicitly defined in the class body or inherited from the base types, it will not be generated.
Which, infact, makes copy
no better than a constructor for Java interop.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With