Data classes

Kotlin language Junior Kotlin 2.0+ API 24+ Reviewed By Best Latest Apps

Predict the output

What does this print?

data class User(val name: String) {
    var visits: Int = 0
}

fun main() {
    val a = User("Ana").apply { visits = 3 }
    val b = User("Ana")
    println(a == b)
    println(a === b)
    println(a)
}
Options
Hint 1 of 1

Which properties are used by the generated functions?

Choose an answer, then open Show answer below to check it.

Show answer

Answer: A true, false, User(name=Ana)

Correct. equals and toString use only constructor properties; === compares identity.

Why not the others?
  • B false, false, User(name=Ana, visits=3). visits is in the body, so it's not part of equals or toString.
  • C true, true, User(name=Ana). They're two different objects.
  • D true, false, User(name=Ana, visits=3). toString ignores body properties too.

30-second answer

A data class generates equals, hashCode, toString, copy and componentN functions from the properties in its primary constructor. That makes it ideal for value-like models and UI state. Properties declared in the body are ignored by those functions, and copy is shallow, so nested mutable objects are shared.

Practise saying it · 30 s. No recording, just a timer

Explain data classes.

Say your answer out loud, then check which of these points you covered:

  • Generated equals, hashCode, toString, copy
  • Only primary constructor properties
  • copy is shallow
  • Use val properties

Deep dive

Data classes can't be abstract, open, sealed or inner; they can implement interfaces and extend open classes.

Use val properties so equals/hashCode stay stable while the object is in a set or map.

copy(x = 1) is how you update immutable state, often inside update { }.

A data class with a MutableList property is still mutable inside.

Common mistakes

  • Expecting body properties to be part of equals.
  • Using var properties and putting the object in a HashSet.
  • Assuming copy() deep-copies nested lists.

Senior take & follow-ups

Mention the primary-constructor rule and shallow copy; those are the traps.

Follow-up questions

Think of your answer first, then open the hint.

  1. What's a data object?

    Show hint

    A singleton with a readable toString and equals, often for sealed hierarchy cases.

  2. Is copy deep or shallow?

    Show hint

    Shallow.

Suggest a fix if something here is wrong or out of date.