Kotlin Tutorial · Object-Oriented Kotlin · Lesson 13 of 31

Kotlin Data Classes

Data classes generate equals, hashCode, toString, copy and destructuring for classes that hold data.

Create a free account to save this page, take notes and track your progress. Sign in

data class

Mark a class data and the compiler generates equals()/hashCode() (by value), a readable toString(), copy() for changed copies, and componentN() functions for destructuring.

What data classes generate
data class Point(val x: Int, val y: Int)

fun main() {
    val a = Point(1, 2)
    val b = Point(1, 2)
    println(a)                 // generated toString
    println(a == b)            // structural equality
    println(a === b)           // different objects
    val (x, y) = a             // destructuring
    println("x=$x y=$y")
    println(setOf(a, b).size)  // equal hash codes
}

Output

Point(x=1, y=2)
true
false
x=1 y=2
1

Run this on your computer — see “Get Started” for setup.

Immutable updates

With val properties, copy() is the usual way to "change" a value: it returns a new object and leaves the old one untouched, which is safe to share between threads and UI state.

copy for immutable updates
data class Order(val id: Int, val status: String, val items: List<String>)

fun main() {
    val placed = Order(42, "placed", listOf("mug"))
    val shipped = placed.copy(status = "shipped")
    println(placed)
    println(shipped)
}

Output

Order(id=42, status=placed, items=[mug])
Order(id=42, status=shipped, items=[mug])

Run this on your computer — see “Get Started” for setup.

Test yourself

Which function do data classes generate to create a modified copy?

  1. clone()
  2. copy()
  3. with()
  4. update()
Show answer

Answer: copy()

Was this page helpful?