Thuta Learning
Kotlin
IntermediateProgrammingBeginner

Data Classes

KotlinLesson 1830 min

What you'll walk away with

  • Declare a data class and name what the compiler generates from it
  • Compare data class values with == and explain why a plain class compares by identity
  • Use copy() to build a changed version, and destructure with componentN
  • Predict which properties take part in equals, toString and copy, and why a shallow copy shares mutable fields

Explain it simply

Explain it simply

A data class is a class whose whole job is to carry data, like a labelled box or one row of a table. You list only the fields, and Kotlin writes the boring methods for you: how to print it, how to compare two boxes, how to make a modified copy of one. Because those methods compare and print contents, two boxes with the same labels and values count as equal.

The price of a data class is one word, data, in front of class. Users, API responses, database rows and UI state are all natural data classes.

Problem → Why → Solution

The problem: identical values that are not equal

Take a plain class User(val name: String, val age: Int) and create two users with identical values. Compare them with == and you get false: for a normal class, == means the same object, not the same contents. Print one and you see User@ followed by a hex number, which tells you nothing, and put one in a HashSet and the other copy is not found. Fixing it by hand means writing equals, hashCode, toString and a copy function, and forgetting hashCode is a classic bug.

plain-user.kt
class User(val name: String, val age: Int)

fun main() {
    val a = User("Alice", 28)
    val b = User("Alice", 28)
    println(a == b)          // false: compares identity, not contents
    println(a)               // User@ followed by a hex number
    val seen = hashSetOf(a)
    println(b in seen)       // false: the set cannot recognise the twin
}

Why is hand-written boilerplate risky?

Writing those methods by hand is repetitive and easy to get subtly wrong: change a field and forget to update equals, and two objects stop comparing correctly. A data class generates all of them from the primary constructor, so they cannot drift out of sync with the fields. That is why the data keyword exists: it states that this class is its contents.

Core concept: a value, not an identity

Mark a class data and the compiler generates five things from the properties in the primary constructor: equals() and hashCode() for content comparison, toString() that prints User(name=Alice, age=28), copy() to make a changed copy, and componentN() functions that enable destructuring. The requirements are small: the primary constructor needs at least one parameter, and every parameter must be val or var. Otherwise the compiler reports "data class must have at least one primary constructor parameter" or "primary constructor of data class must only have property ('val' / 'var') parameters".

The detail that surprises people is that only primary-constructor properties take part. A property declared in the class body is ignored by equals, hashCode, toString, copy and componentN. Two profiles with different lastSeen values declared in the body are still equal, and copy() gives the new object that property's initial value. That is useful for cached or derived state, but dangerous if the body property is real data.

copy() takes named, defaulted parameters, one per property, so user.copy(name = "Bob") changes one field and keeps the rest. It is a shallow copy: if a property holds a mutable list, the copy and the original hold the same list. Prefer val properties and read-only collection types so that sharing is harmless. Destructuring val (name, age) = user uses component1() and component2(), assigned by position, not by name. Reorder the properties and every destructuring site silently changes meaning when the types match.

Be careful with data classes as HashMap keys or HashSet members. The hash code is computed from the property values, so changing a var property after insertion changes the hash and the object is lost inside the set. Use val properties in anything that will be a key. Also, a data class can implement interfaces and have functions, but it cannot be open, abstract, sealed or inner, which keeps value semantics simple.

Generated memberWhat it usesExample
toString()Primary propertiesUser(name=Alice, age=28)
equals() / hashCode()Primary propertiesUser("A", 1) == User("A", 1) is true
copy(...)Primary properties as defaultsuser.copy(age = 29)
componentN()Primary properties, by positionval (name, age) = user
Mental model: a value, not an identity
  1. List the fields in the primary constructor
  2. The compiler writes five members from them
  3. Equal contents mean equal objects
  4. copy() makes a changed twin

What tells two data class objects apart is the values of their fields, not their place in memory.

General pattern

kotlin
data class Name(val first: Type, val second: Type = defaultValue) {
    // properties declared here are NOT part of equals, toString or copy
}

val a = Name(x, y)
val b = a.copy(first = newValue)     // changed twin, other fields kept
val same = a == Name(x, y)           // compares contents
val (p, q) = a                       // component1(), component2()

Only the properties in the primary constructor appear in the generated members. copy() changes just the named fields and keeps the rest. == compares contents, and (p, q) = a uses component1() and component2() in order.

Example: copying, comparing and destructuring

Let us see what a User data class gives you automatically. user2 is built with user1.copy(name = "Bob"), so age is carried over without being repeated. println calls toString() and shows a readable form. == compares contents, so it is true even against a brand-new User("Alice", 28), and val (name, age) splits user2 apart.

UserDemo.kt
data class User(val name: String, val age: Int)

fun main() {
    val user1 = User("Alice", 28)
    val user2 = user1.copy(name = "Bob")

    println(user1)
    println(user2)
    println(user1 == User("Alice", 28))
    val (name, age) = user2
    println("$name is $age")
}

Code breakdown

  1. Declare the data classdata class User(val name: String, val age: Int)

    Because of data, the compiler generates toString, equals, hashCode, copy and component1/component2 from name and age. No body is needed, so there are no braces.

  2. Copy with one changeval user2 = user1.copy(name = "Bob")

    copy leaves user1 alone and returns a new User with name replaced by Bob and age carried over, so user1 is still Alice. "Changing" immutable data means building a changed copy.

  3. Readable printingprintln(user1)

    This calls toString() and prints User(name=Alice, age=28). A plain class would print only User@ and a hex number. That readability is why logs and test failure messages are useful.

  4. Compare contentsprintln(user1 == User("Alice", 28))

    == calls equals() and compares the primary properties one by one, so it prints true even though the object is new. To ask whether two references are the very same object, use ===.

  5. Destructureval (name, age) = user2

    This calls component1() and component2() and creates two variables, by position and not by name. Writing (age, name) would still compile and quietly put the name into age; you would notice only when the differing types break a later line, and with same-typed fields you would not notice at all.

You should see
User(name=Alice, age=28)
User(name=Bob, age=28)
true
Bob is 28
What happens when you evaluate a == b
  1. a == b is evaluated
  2. equals() compares the primary properties one by one
  3. Are all of them equal?

All equal

the result is true, even for two different objects

Any difference

the result is false

What counts as the data, and how deep copy goes

In Profile, name and tags are in the primary constructor while lastSeen lives in the body. So a == b is true even when lastSeen differs, and printing leaves lastSeen out. a.copy() does not carry lastSeen over either, so c.lastSeen goes back to "never". And c.tags.add("beta") changes a.tags too: copy() copies the reference to the list, not the list itself, so both objects share one list.

what-counts.kt
data class Profile(val name: String, val tags: MutableList<String>) {
    var lastSeen: String = "never"          // body property: not part of the data
}

fun main() {
    val a = Profile("Aye", mutableListOf("admin"))
    a.lastSeen = "monday"
    val b = Profile("Aye", mutableListOf("admin"))

    println(a == b)                 // true: lastSeen is not in the primary constructor
    println(a)                      // Profile(name=Aye, tags=[admin])
    println(b.lastSeen)             // never
    val c = a.copy()
    println(c.lastSeen)             // never: copy() passes only constructor properties
    c.tags.add("beta")              // shallow copy: the very same list object
    println(a.tags)                 // [admin, beta]
}

Data classes in collections and destructuring

Content-based equality makes data classes work well with collections. items.toSet() collapses equal items into one, and distinct() and associateBy build further groupings. items.map { it.copy(qty = it.qty + 10) } builds a new list of changed items and leaves the old list untouched. for ((sku, price, qty) in ...) splits each item from component1 to component3 into three named variables. These are everyday patterns in UI state and test data.

collections.kt
data class Item(val sku: String, val price: Int, val qty: Int)

fun main() {
    val items = listOf(
        Item("A1", 10, 2),
        Item("B2", 5, 1),
        Item("A1", 10, 2),
        Item("C3", 5, 4),
    )
    println(items.toSet().size)                      // 3: equal items collapse in a Set
    val bySku = items.distinct().associateBy { it.sku }
    println(bySku["B2"])
    val restocked = items.map { it.copy(qty = it.qty + 10) }
    println(restocked.first())
    for ((sku, price, qty) in items.distinct()) println("$sku: ${price * qty}")
    val groups = items.groupBy { it.price }
    println(groups.keys)
}

In real projects

Where this shows up in real projects

Data classes are used more often than people expect. JSON libraries such as kotlinx.serialization, Moshi and Jackson map an API response straight onto the constructor properties of a data class. A database row is naturally a data class, so query results become simple lists. In tests, assertEquals(expected, actual) compares values and, on a mismatch, prints a readable message such as User(name=Alice, age=28).

UI state is also usually a data class. A screen's state is declared with val fields, and every change builds a new copy, as in state = state.copy(loading = false). The framework can then compare old and new with == and redraw only when something changed. A data class is a poor fit for entities that have an identity, though: two orders with identical fields may be genuinely different orders, and when an id must tell them apart, a plain class is the better choice.

Common mistakes

Common mistakes

1. Expecting body properties in equals and copy

In data class Profile(val name: String) { var visits = 0 }, visits is not part of equals, toString or copy. Two Profile("Aye") objects with different visits are still equal, and copy() resets visits to 0. If it is real data, move it into the constructor.

2. Forgetting that a shallow copy shares mutable lists

After val b = a.copy(), b.members.add(2) also changes a.members. Declare the property as a read-only List<Int>, and when you need a change, build a new list such as members + 2 and pass it with copy(members = ...).

3. Changing a var property of a key already in a set

The hash code depends on the property values, so changing id after insertion makes the set unable to find the object, yet it still counts toward the size. The snippet below shows it. Write any data class that will be a set member or map key with val properties only.

4. Reordering properties without checking destructuring

Destructuring works by position, not by name. Changing Item(sku, price, qty) to Item(sku, qty, price) leaves the compiler silent, because both are Int, while the values quietly swap. Beyond two fields, reading by name is safer than relying on componentN.

mutable-key.kt
data class Key(var id: Int)

fun main() {
    val k = Key(1)
    val set = hashSetOf(k)
    println(k in set)               // true
    k.id = 2
    println(k in set)               // false: the hash changed, the object is lost
    println(set.size)               // 1: it is still in there
    println(set.contains(Key(1)))   // false: an equal-looking key is not found either
}

Best practices

Best practices

  • Declare data class properties as val and build a changed object with copy() instead of mutating.
  • Prefer read-only types such as List over MutableList so that the sharing in a shallow copy is harmless.
  • Do not use a data class for entities with an identity, such as an order or account told apart by id; use it for small values such as Point, Money or Address.

Mini challenge

Mini challenge: a task list

Work with a Task data class and a task list: remove duplicates, mark high-priority tasks as done and print the result with destructuring.

  • Declare data class Task(title, priority = 1, done = false)
  • complete(task) returns a copy with done = true and leaves the original task unchanged
  • Turn the list into a set to remove duplicates, then complete every task with priority 2 or higher
  • Print every task by destructuring it, then the titles of completed tasks, then whether tasks[0] equals its completed copy with done set back to false
tasks.kt
// TODO: data class Task(title, priority = 1, done = false)

fun complete(task: Task): Task {
    // TODO: return a copy with done = true
}

fun main() {
    // TODO: four tasks: "write report" (priority 2) twice, "email Aye", "book flight" (3)
    // TODO: remove duplicates by going through a set, print how many remain
    // TODO: complete every task with priority >= 2, print each as "title pN done=..."
    // TODO: print the titles of the completed tasks (groupBy done)
    // TODO: print tasks[0] == complete(tasks[0]).copy(done = false)
}

Expected: The program prints these six lines: 3 write report p2 done=true email Aye p1 done=false book flight p3 done=true [write report, book flight] true

Show hint

Remove duplicates with tasks.toSet().toList(). Destructure with for ((title, priority, done) in updated). groupBy { it.done } gives a Map<Boolean, List<Task>>, so getValue(true).map { it.title } collects the titles.

Show solution
tasks.kt
data class Task(val title: String, val priority: Int = 1, val done: Boolean = false)

fun complete(task: Task): Task = task.copy(done = true)

fun main() {
    val tasks = listOf(
        Task("write report", 2),
        Task("email Aye"),
        Task("write report", 2),
        Task("book flight", 3),
    )
    val unique = tasks.toSet().toList()
    println(unique.size)
    val updated = unique.map { if (it.priority >= 2) complete(it) else it }
    for ((title, priority, done) in updated) println("$title p$priority done=$done")
    val byDone = updated.groupBy { it.done }
    println(byDone.getValue(true).map { it.title })
    println(tasks[0] == complete(tasks[0]).copy(done = false))
}

Quick quiz 1 / 3

For data class Point(val x: Int, val y: Int), what do println(Point(1, 2) == Point(1, 2)) and println(Point(1, 2) === Point(1, 2)) print?

Quick quiz 2 / 3

With data class Profile(val name: String) { var visits = 0 } and val p1 = Profile("Aye"); p1.visits = 5, what does println(p1 == Profile("Aye")) print?

Quick quiz 3 / 3

With data class Team(val name: String, val members: MutableList<Int>), after val a = Team("x", mutableListOf(1)); val b = a.copy(); b.members.add(2), what does println(a.members) print?

What to remember

  • A data class generates equals, hashCode, toString, copy and componentN from its primary-constructor properties, and == compares contents.
  • The primary constructor needs at least one parameter and all must be val or var; properties declared in the body take no part.
  • copy() builds a new object with chosen properties changed, but it is shallow and shares mutable lists.
  • Use only val properties for set or map keys, and remember that destructuring works by position, not by name.

Kotlin language guide — Kotlin

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Data Classes | Thuta Learning