← Back to Kotlin Course | Chapter 6: Classes & Objects | Lesson 5 of 7

Data Classes

A data class is a special shortcut for classes that just hold information, so Kotlin automatically writes the boring comparison and printing code for you.

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

markup
data class Point(val x: Int, val y: Int)

fun main() {
    val p = Point(3, 4)
    println(p)
}

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()

markup
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}")
}

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

markup
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")
}

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

markup
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")
}
Common Mistakes
  1. Writing a normal class and manually implementing equals, hashCode, and toString when data class would generate all three for free.
  2. Forgetting that copy() performs a shallow copy, so mutable properties referencing the same nested object are still shared between the original and the copy.
  3. Putting properties outside the primary constructor and expecting them to be included in the generated equals/toString; only constructor properties are included.
Chapter Summary
  • data class automatically generates equals(), hashCode(), toString(), and a copy() 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.