A data class in Kotlin is a specialized class whose primary purpose is to hold state, for which the compiler automatically generates standard utility functions based on the properties defined in the primary constructor.Documentation Index
Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
Use this file to discover all available pages before exploring further.
data keyword, the Kotlin compiler automatically derives the following member functions using only the properties declared in the primary constructor:
equals(): Evaluates structural equality, comparing the values of the properties rather than the object references in memory.hashCode(): Generates a hash code consistent withequals(). If two instances are structurally equal, they will produce the same hash code.toString(): Returns a string representation of the object in the format"ClassName(prop1=value1, prop2=value2)".componentN(): Generates functions (component1(),component2(), etc.) corresponding to the properties in their order of declaration. This enables destructuring declarations.copy(): Creates a new instance of the object, allowing the modification of specific properties while retaining the values of the rest.
Strict Compiler Requirements
To ensure the deterministic generation of these utility functions, data classes must adhere to the following rules:- The primary constructor must have at least one parameter.
- All primary constructor parameters must be explicitly marked as
val(read-only) orvar(mutable). - Data classes cannot be
abstract,open,sealed, orinner.
Class Body Properties Exclusion
The compiler strictly limits the scope of generated functions to the primary constructor. Properties declared within the class body are entirely excluded from the generatedequals(), hashCode(), toString(), copy(), and componentN() implementations.
Inheritance
Data classes can extend other classes and implement interfaces. However, if the generated methods (equals, hashCode, or toString) are explicitly implemented in the data class body or are final in a superclass, the compiler will not generate them and will use the existing implementations instead.
Master Kotlin with Deep Grasping Methodology!Learn More





