DEV Community

Fredydoss
Fredydoss

Posted on

Kotlin data class — Behind the mask

As the name states, a data class is a class that holds data. The difference from the normal class is the auto-generation of some standard functionality and utility functions derived from the data itself.

  1. copy()
  2. componentN()
  3. copy$default — A synthetic method

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

2) componentN()The ability to use destructuring declaration of data class is due to the generated component functions.
componentN() functions corresponding to the properties in their order of declaration;
If you are familiar with the principles of conversions widely used in kotlin, then component functions are one among them. If the required number of components functions can be called, then anything can be on the right-hand side of the destructuring declaration.

3) copy$default
Java synthetic classes, methods and fields are for java runtime’s internal purposes. We may not need to have knowledge about them to write the code.
When an enclosing class accesses a private attribute of a nested class, Java compiler creates synthetic method for that attribute. If there is a getter method available in source then this synthetic method will not be created.
We don’t care about this method as it’s used internally on runtime by the JVM.

Top comments (0)