Kotlin Data Classes โ Automatic equals, toString, and copy
A data class is a class whose main purpose is to hold data. Kotlin auto-generates toString, equals, hashCode, copy, and destructuring.
What You Will Learn
- Declare a data class
- Use auto-generated toString and equals
- Copy with modified properties using copy()
- Destructure data class instances
Declaring a Data Class
Data Class
data class User(val id: Int, val name: String, val email: String)
fun main() {
val user = User(1, "Juned", "juned@example.com")
println(user) // auto toString
println(user.name)
}toString() is auto-generated and shows all property values. No need to write it manually.
equals and hashCode
Structural Equality
data class Point(val x: Int, val y: Int)
fun main() {
val p1 = Point(3, 4)
val p2 = Point(3, 4)
val p3 = Point(5, 6)
println(p1 == p2) // structural equality
println(p1 == p3)
println(p1 === p2) // reference equality
}== on data classes compares property values. p1 and p2 have the same values, so == returns true. === checks if they are the same object in memory โ they are not.
copy() Function
copy()
data class Config(val host: String, val port: Int, val debug: Boolean = false)
fun main() {
val prod = Config("prod.example.com", 443)
val dev = prod.copy(host = "localhost", port = 8080, debug = true)
println(prod)
println(dev)
}copy() creates a new instance with specified properties changed. Unspecified properties keep the original value. prod is unchanged.
Destructuring
Destructuring
data class Point(val x: Int, val y: Int)
fun main() {
val p = Point(10, 20)
val (x, y) = p
println("x=$x, y=$y")
}(x, y) = p destructures the Point. Kotlin generates component1() for x and component2() for y.
Practice Exercise
What prints? data class Cat(val name: String, val age: Int) val c = Cat("Whiskers", 3) val c2 = c.copy(age = 4) println(c2)
Quick Quiz
Which functions does a data class auto-generate?
Frequently Asked Questions
Related Tutorials
Written by KotlinGuide Editorial Team ยท Reviewed by KotlinGuide Technical Review