Beginner 7 min readKotlin 2.0

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

Add the data modifier before class. The compiler generates useful functions automatically.

Data Class

kotlin
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)
}
Output
User(id=1, name=Juned, email=juned@example.com) Juned

toString() is auto-generated and shows all property values. No need to write it manually.

Beginner Tip: Data classes are perfect for API responses, database records, UI state, and any object that primarily holds values.

equals and hashCode

Data classes compare by value, not by reference.

Structural Equality

kotlin
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
}
Output
true false false

== 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

Create a modified copy without changing the original.

copy()

kotlin
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)
}
Output
Config(host=prod.example.com, port=443, debug=false) Config(host=localhost, port=8080, debug=true)

copy() creates a new instance with specified properties changed. Unspecified properties keep the original value. prod is unchanged.

Destructuring

Unpack a data class into individual variables.

Destructuring

kotlin
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")
}
Output
x=10, y=20

(x, y) = p destructures the Point. Kotlin generates component1() for x and component2() for y.

Practice Exercise

Exercisepredict output

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

Quick Quiz

Which functions does a data class auto-generate?

Frequently Asked Questions

Related Tutorials

Last updated: 2026-05-01Kotlin 2.0

Written by KotlinGuide Editorial Team ยท Reviewed by KotlinGuide Technical Review