A data class is a class whose main job is to hold data, such as a user, a product or an API response. Add the word data, and Kotlin writes the boring code for you.
Page Contents
Regular class vs data class
class PointA(val x: Int, val y: Int)
data class PointB(val x: Int, val y: Int)
fun main() {
println(PointA(1, 2)) // class name and a hash code
println(PointB(1, 2)) // readable
println(PointA(1, 2) == PointA(1, 2)) // compares objects
println(PointB(1, 2) == PointB(1, 2)) // compares values
}Output:
PointA@6bc7c054 PointB(x=1, y=2) false true
The number after @ is a hash code, and it will be different when you run it.
What a data class gives you
For every property in the primary constructor, Kotlin generates:
| Function | What it does |
|---|---|
toString() | User(name=Asha, age=25) |
equals() / == | equal when all the properties are equal |
hashCode() | consistent with equals, so sets and maps work |
copy() | a copy with some properties changed |
component1(), component2()… | allow destructuring |
copy: change one thing, keep the rest
Data classes are usually immutable (val properties). To “change” one, make a modified copy:
data class User(val name: String, val email: String, val isPremium: Boolean = false)
fun main() {
val user = User("Ravi", "ravi@example.com")
val upgraded = user.copy(isPremium = true)
println(user)
println(upgraded)
}Output:
User(name=Ravi, email=ravi@example.com, isPremium=false) User(name=Ravi, email=ravi@example.com, isPremium=true)
This is exactly how state is updated in Jetpack Compose and ViewModels: state = state.copy(isLoading = false).
Destructuring
data class Product(val name: String, val price: Int)
fun main() {
val (name, price) = Product("Keyboard", 1299)
println("$name costs ₹$price")
val cart = listOf(Product("Mouse", 599), Product("Pad", 199))
for ((n, p) in cart) println("$n: ₹$p")
}Output:
Keyboard costs ₹1299 Mouse: ₹599 Pad: ₹199
Equality in sets and maps
Because equals and hashCode compare values, data classes work well as set items and map keys:
data class Seat(val row: Char, val number: Int)
fun main() {
val booked = mutableSetOf(Seat('A', 1), Seat('A', 2))
println(Seat('A', 1) in booked)
println(booked.add(Seat('A', 2))) // false: already there
val prices = mapOf(Seat('A', 1) to 450, Seat('B', 5) to 300)
println(prices[Seat('B', 5)])
}Output:
true false 300
Only constructor properties count
Properties declared in the class body are not used by equals, toString or copy:
data class Task(val title: String) {
var done = false
}
fun main() {
val a = Task("Write lesson")
val b = Task("Write lesson")
b.done = true
println(a == b) // true: done isn't compared
println(b) // done isn't printed
}Output:
true Task(title=Write lesson)
Rules for data classes
- The primary constructor needs at least one parameter, and every parameter must be
valorvar. - A data class can’t be
abstract,open,sealedorinner. - It can implement interfaces and extend other (non-data) classes.
Data classes in real apps
data class UiState(
val isLoading: Boolean = false,
val items: List<String> = emptyList(),
val error: String? = null
)
fun main() {
var state = UiState(isLoading = true)
println(state)
state = state.copy(isLoading = false, items = listOf("Kotlin", "Compose"))
println(state)
}Output:
UiState(isLoading=true, items=[], error=null) UiState(isLoading=false, items=[Kotlin, Compose], error=null)
Data classes are also used for API responses (see JSON to Kotlin data class) and Room database entities.
Common mistakes
- Using
vareverywhere: mutable data classes can change while they’re inside a set or map, which breaks lookups. Prefervalandcopy(). - Expecting body properties in
equals: only constructor properties count. - Making every class a data class: a class with important behavior and identity (like a
Databaseor aViewModel) shouldn’t be one.
Exercise
Model a cart item, update its quantity with copy, remove duplicates with a set, and print the total.
data class CartItem(val id: Int, val name: String, val price: Int, val qty: Int = 1)
fun main() {
val items = listOf(
CartItem(1, "Mouse", 599),
CartItem(2, "Keyboard", 1299),
CartItem(1, "Mouse", 599) // duplicate
)
val unique = items.toSet().toMutableList()
unique[0] = unique[0].copy(qty = 2)
unique.forEach { println("${it.name} x${it.qty} = ₹${it.price * it.qty}") }
println("Total: ₹${unique.sumOf { it.price * it.qty }}")
}Output:
Mouse x2 = ₹1198 Keyboard x1 = ₹1299 Total: ₹2497
FAQ
What is a data class in Kotlin?
A class declared with data that automatically gets equals, hashCode, toString, copy and destructuring for its constructor properties.
What does copy() do in a Kotlin data class?
It creates a new object with the same values, except for the properties you change: user.copy(age = 30).
Can a data class be inherited from?
No. Data classes can’t be open. They can implement interfaces, though.
