This question is high in search rankings, and potentially confusing for those new to kotlin, since the question's sample code is not typical kotlin code or usage of the copy function. I added some sample code below to help clarify what's going on, and also show typical usage of a data class.
In short, the copy function is most useful when called from a kotlin class. I agree that its behavior isn't obvious when called from java code.
//
// A.kt
//
// this is an idiomatic kotlin data class. note the parens around the properties, not braces.
data class A(
val x: String? = null,
val y: String? = null,
val z: B = B.ONE
) {
// this javaCopy function is completely unnecessary when being called from kotlin; it's only here to show a fairly simple way to make kotlin-java interop a little easier (like what Nokuap showed).
fun javaCopy(): A {
return this.copy()
}
}
enum class B {
ONE,
TWO,
THREE
}
fun main() {
val a1 = A("Hello", "World", B.TWO)
// here's what copy usage looks like for idiomatic kotlin code.
val a2 = a1.copy()
assert(a2.x == "Hello")
assert(a2.y == "World")
assert(a2.z == B.TWO)
// more typical is to `copy` the object and modify one or more properties during the copy. e.g.:
val a3 = a1.copy(y = "Friend")
assert(a2.x == "Hello")
assert(a3.y == "Friend")
}
public class App {
public static void main(String[] args) {
A a1 = new A("Hello", "World", B.TWO);
// the kotlin copy function is primarily meant for kotlin <-> kotlin interop
// copy works when called from java, but it requires all the args.
// calling the `javaCopy` function gives the expected behavior.
A a2 = a1.javaCopy();
assert a2.getX().equals("Hello");
assert a2.getY().equals("World");
assert a2.getZ().equals(B.TWO);
}
}
Official docs on data classes, including the copy function:
https://kotlinlang.org/docs/reference/data-classes.html