Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 273
Michael Pardo Avatar asked Feb 20 '15 02:02

Michael Pardo


People also ask

Can I use Kotlin data class in Java?

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

Can Kotlin data classes have functions?

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.

How does copy work in Kotlin?

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.

Is Kotlin copy a deep copy?

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.


1 Answers

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.

like image 178
Michael Pardo Avatar answered Oct 06 '22 10:10

Michael Pardo