What is a data class in Kotlin?
- tool
- Kotlin
- versions
- Kotlin 1.x – 2.x
- os
- any
A data class in Kotlin is a class declared with data class whose main job is to hold values. From the properties in its primary constructor, the compiler generates equals() and hashCode() (compare by value), a readable toString() such as User(name=Ada, age=36), componentN() functions for destructuring, and copy() to create a modified copy. It is Kotlin's equivalent of a Java record or a C# record.
Example
data class User(val name: String, val age: Int)
fun main() {
val a = User("Ada", 36)
val b = User("Ada", 36)
println(a == b) // true: equals() compares properties
println(a) // User(name=Ada, age=36)
val older = a.copy(age = 37) // new object, one property changed
val (name, age) = older // destructuring via component1(), component2()
println("$name $age") // Ada 37
}Rules
| Rule | Detail |
|---|---|
| Primary constructor | Needs at least one parameter, each marked val or var |
| Generated members | equals(), hashCode(), toString(), componentN(), copy() |
| Properties in the class body | Not part of equals, hashCode, toString or copy |
| Modifiers | A data class cannot be abstract, open, sealed or inner |
| Inheritance | It can extend other classes and implement interfaces |
When to use one
Use a data class for values compared by content: API models, database rows, UI state, map keys, results with several fields. Use val properties so the object stays immutable and safe as a key; change it with copy(). A regular class is better for objects with identity and behaviour, such as services or entities whose equality should not depend on every field.