Data Class (Kotlin)
A data class is a class meant to hold data. Adding the data keyword makes Kotlin auto-generate equals(), hashCode(), toString(), copy(), and componentN() from the primary constructor properties.
Kotlin
Declaring data class User(val name: String, val age: Int) gives you value-style equality (two users with the same fields are equal), a readable toString, a copy() for making modified duplicates, and destructuring support — all without boilerplate.
copy() is especially useful with immutable data: user.copy(age = 31) returns a new instance with one field changed, leaving the original untouched. The componentN() functions enable destructuring: val (name, age) = user.
Data classes are perfect for DTOs, API models, and any plain value holder. They must have at least one primary-constructor parameter, and only properties declared there participate in the generated methods. For richer behavior or hierarchies, use a regular or sealed class.
Syntax
data class User(val name: String, val age: Int)Examples
Kotlin
data class Point(val x: Int, val y: Int)
val a = Point(1, 2)
val b = a.copy(y = 5)
println(a)
println(b)
println(a == Point(1, 2))Output:
Point(x=1, y=2)
Point(x=1, y=5)
true