Search code examples
javakotlindata-class

Kotlin data class copy function not working when called from java class


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.


Solution

  • 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.