Skip to main content

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.

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.
data class User(val name: String, var age: Int)
When a class is marked with the 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 with equals(). 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.
val user1 = User("Alice", 25)

// Utilizing the generated copy() function
val user2 = user1.copy(age = 26) 

// Utilizing the generated componentN() functions via destructuring
val (name, age) = user1 

Strict Compiler Requirements

To ensure the deterministic generation of these utility functions, data classes must adhere to the following rules:
  1. The primary constructor must have at least one parameter.
  2. All primary constructor parameters must be explicitly marked as val (read-only) or var (mutable).
  3. Data classes cannot be abstract, open, sealed, or inner.

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 generated equals(), hashCode(), toString(), copy(), and componentN() implementations.
data class Person(val name: String) {
    // This property is ignored by all compiler-generated data class functions
    var age: Int = 0 
}

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