Data Classes
In this page:
Declaring a Data Class
Adding data before class tells the compiler to generate useful boilerplate -- equals(), hashCode(), and toString() -- based on the properties in the primary constructor.
Example: Declaring a Data Class
data class Point(val x: Int, val y: Int)
fun main() {
val p = Point(3, 4)
println(p)
}
Login to try C/C++/Java/PHP code in the editor
Automatic equals() and hashCode()
Two data class instances with the same property values are considered equal by ==, since equals() is generated to compare all constructor properties.
Example: Automatic equals() and hashCode()
data class Point(val x: Int, val y: Int)
fun main() {
val p1 = Point(1, 2)
val p2 = Point(1, 2)
println("Equal: ${p1 == p2}")
}
Login to try C/C++/Java/PHP code in the editor
Copying with Modifications
The generated copy() function creates a new instance with the same property values, letting you override just the ones you want to change.
Example: Copying with Modifications
data class User(val name: String, val age: Int)
fun main() {
val original = User("Ana", 30)
val older = original.copy(age = 31)
println("$original -> $older")
}
Login to try C/C++/Java/PHP code in the editor
Destructuring a Data Class
Data classes automatically support destructuring declarations, letting you unpack their properties into separate variables in the order they were declared.
Example: Destructuring a Data Class
data class Point(val x: Int, val y: Int)
fun main() {
val point = Point(5, 10)
val (x, y) = point
println("x=$x, y=$y")
}
Login to try C/C++/Java/PHP code in the editor
- Writing a normal
classand manually implementingequals,hashCode, andtoStringwhendata classwould generate all three for free. - Forgetting that
copy()performs a shallow copy, so mutable properties referencing the same nested object are still shared between the original and the copy. - Putting properties outside the primary constructor and expecting them to be included in the generated
equals/toString; only constructor properties are included.
data classautomatically generatesequals(),hashCode(),toString(), and acopy()function based on primary constructor properties.copy()creates a new instance with the same values, optionally overriding specific properties.- Data classes also support destructuring into multiple variables via
componentN()functions. - Only properties declared in the primary constructor participate in the generated functions.
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: