Data classes in Kotlin are primarily used to hold data. For each data class, the compiler automatically generates additional member functions that allow you to print an instance to readable output, compare instances, copy instances, and more. Data classes are marked with data:
Data classes can't be abstract, open, sealed, or inner.
data class User(val name: String, val age: Int)
The compiler automatically derives the following members from all properties declared in the primary constructor:
.equals()/.hashCode() pair.
.toString() of the form "User(name=John, age=42)".
.componentN() functions corresponding to the properties in their order of declaration.
.copy() function (see below).
To ensure consistency and meaningful behavior of the generated code, data classes have to fulfill the following requirements:
The primary constructor must have at least one parameter.
All primary constructor parameters must be marked as val or var.
Data classes can't be abstract, open, sealed, or inner
Additionally, the generation of data class members follows these rules with regard to the members' inheritance:
If there are explicit implementations of .equals(), .hashCode(), or .toString() in the data class body or final implementations in a superclass, then these functions are not generated, and the existing implementations are used.
Providing explicit implementations for the .componentN() and .copy() functions is not allowed.
In the example below, only the name property is used by default inside the .toString(), .equals(), .hashCode(), and .copy() implementations, and there is only one component function, .component1(). The age property is declared inside the class body and is excluded. Therefore, two Person objects with the same name but different age values are considered equal since .equals() only evaluates properties from the primary constructor:
Data class reduce the boilerplate code of declaring getters & setters for each class member field
Unlike java. here p1==p2 returns true. as data class override the == operator(calls .equals()). Data class override the equals method of any class and it can compare the object's data rather than its references.
Data class has copy function which copy the object with various variation
Destructuring
We can destructure data of data class into variables.
values of p1 assigned into id and name variable of val type
it has component() method also which prints the fields of data class