What is a Data Class?
A Data Class is a class whose main purpose is to hold data. In Java, this usually requires writing dozens of lines of boilerplate (
getters, setters, toString, equals, hashCode). In Kotlin, you just add the data keyword.kotlin
Wait! With just one line, Kotlin gives you:
equals()/hashCode(): Compares the data, not the memory address.toString(): ReturnsUser(name=Alpha, age=25).copy(): Creates a copy with some modified values.componentN(): Allows for destructuring.
The copy() Function
Wait! Because data classes are often used as immutable models, the
copy() function is incredibly useful for "changing" data safely.kotlin
Destructuring Declarations
You can "unpack" a data class directly into variables.
kotlin
Requirements
To be a data class:
- The primary constructor must have at least one parameter.
- All primary constructor parameters must be marked as
valorvar. - Data classes cannot be
abstract,open, orsealed.
Summary
| Term | Description |
|---|---|
| data | Keyword that enables automatic method generation |
| copy | Creating a modified clone of an object |
| equals | Value-based equality check |
| destruct | val (x, y) = obj syntax |
| Best For | Models, DTOs (Data Transfer Objects), and App State |
| Logic | "Data is the focus" |
| Safety | Promotes immutability and predictable data handling |
| Modern | Replaces heavy boilerplate with a single keyword |
| Standard | Use data class for any class that just holds information |
| Identity | Based on the values inside the object |
| Efficiency | Optimized by the compiler to be as fast as manual code |