Kotlin Data Classes
Many classes exist mainly to hold data: a user, an order line, a coordinate. For such classes you usually want readable printing, comparison by value, hashing and easy copying. Kotlin's data class generates all of that from a single line.
Declaring a data class
data class User(val name: String, val age: Int)
fun main() {
val u1 = User("Ana", 29)
val u2 = User("Ana", 29)
println(u1) // readable toString
println(u1 == u2) // equality by value
println(u1.hashCode() == u2.hashCode())
}User(name=Ana, age=29)
true
true
Compare with a normal class, which would print something like User@1b6d3586 and report false for u1 == u2.
What the compiler generates
| Generated member | What it does |
|---|---|
toString() |
User(name=Ana, age=29) |
equals() / hashCode() |
compare/hash by the primary-constructor properties |
copy(...) |
a new object with some properties changed |
component1(), component2(), … |
enable destructuring val (name, age) = user |
Requirements: the primary constructor needs at least one parameter, and all its parameters must be val or var. Data classes can't be abstract, open, sealed or inner.
copy
Data classes are usually immutable (val properties). To "change" one, make a modified copy — the original stays untouched:
data class Order(val id: Int, val item: String, val qty: Int, val status: String = "new")
fun main() {
val order = Order(1, "Notebook", 2)
val shipped = order.copy(status = "shipped")
val bigger = order.copy(qty = 5)
println(order)
println(shipped)
println(bigger)
}Order(id=1, item=Notebook, qty=2, status=new)
Order(id=1, item=Notebook, qty=2, status=shipped)
Order(id=1, item=Notebook, qty=5, status=new)
Destructuring
The generated componentN() functions let you unpack a data object into variables in one go:
data class Point(val x: Int, val y: Int)
fun main() {
val p = Point(3, 7)
val (x, y) = p
println("x=$x, y=$y")
val path = listOf(Point(0, 0), Point(2, 1), Point(4, 4))
for ((px, py) in path) println("($px|$py)")
}x=3, y=7
(0|0)
(2|1)
(4|4)
Data classes in collections
Because equals and hashCode compare values, data classes work perfectly as set elements and map keys:
data class Product(val sku: String, val name: String)
fun main() {
val cart = listOf(
Product("A1", "Pen"),
Product("B2", "Pad"),
Product("A1", "Pen")
)
println(cart.toSet().size)
println(Product("B2", "Pad") in cart)
println(cart.distinct())
}2
true
[Product(sku=A1, name=Pen), Product(sku=B2, name=Pad)]
Only constructor properties count
Properties declared in the class body are ignored by the generated functions:
data class Visit(val page: String) {
var seconds = 0
}
fun main() {
val a = Visit("/home").apply { seconds = 10 }
val b = Visit("/home").apply { seconds = 99 }
println(a == b)
println(a)
}true
Visit(page=/home)
Tip: Keep data classes immutable (
vals) and usecopyfor changes. Immutable values are safe to share, cache and use as map keys.
Note: Data classes are like Java's
records, but they additionally offercopyand can havevarproperties and default values.
Test yourself
What does println(Person("Li", 30)) print for data class Person(val name: String, val age: Int)?
- Person@6d06d69c
- Person(name=Li, age=30)
- {name: Li, age: 30}
- Li 30
How do you create a modified version of a data object?
- obj.clone()
- obj.copy(age = 31)
- obj.with(age = 31)
- obj.age = 31 always
Which properties are used by a data class's generated equals?
- All properties
- Only properties in the primary constructor
- Only var properties
- None; it compares references