Data classes
A Kotlin data class is a class marked data for which the compiler itself generates equals, hashCode, toString, copy, and componentN functions. The point is to spare you hand-written boilerplate for "data holders" and to give objects structural equality: two instances with the same fields are considered equal.
The traps hide in the details. Generation covers only primary-constructor properties — a property declared in the body takes part in neither equals nor hashCode. And a nested field is compared by its own rules: if it is an ordinary (non-data) class, it is compared by reference and breaks equality of the whole object. On top of that sits the "equals agrees with hashCode" contract, without which lookups in HashMap and HashSet break. The full map is in the layers below.
Topic map
- Generated members of a data class — what
data classgenerates (equals,hashCode,toString,copy,componentN) and why only primary-constructor properties. - The equals ↔ hashCode contract — the consistency rule between
equalsandhashCodeand what breaks inHashMap/HashSetwhen it is violated.
Common traps
| Mistake | Consequence |
|---|---|
Thinking body-declared properties enter equals | A field like val id = ... in the body is silently excluded from equality |
Assuming a nested non-data field is compared by value | An ordinary class compares by reference — the object stops being equal to its own copy |
Overriding equals and forgetting hashCode | Equal objects get different hashes and are lost as keys in HashMap/HashSet |
| Putting a mutable key field into a data class | Mutating after insertion changes hashCode, and the key "vanishes" from the map |
Assuming copy copies body-declared fields | copy takes parameters only for primary-constructor properties |
Interview relevance
Data classes are asked to check whether you understand that autogeneration is not "equals everything to everything" magic but a strictly defined set of members from a strictly defined set of properties. A candidate who immediately says "primary constructor only" and "equals must agree with hashCode" looks stronger than one who says "a data class just compares everything".
Typical checks:
- What exactly
data classgenerates and from which properties. - Why a body-declared field does not affect equality or
copy. - The
equals/hashCodecontract and why breaking it breaksHashMap. - How a nested non-
datafield behaves inside a data class.
Common wrong answer: "a data class compares all of an object's fields by value". In fact only primary-constructor properties enter equals/hashCode, and a nested field is compared by the rules of its type — an ordinary class by reference, so two "identical" objects easily turn out unequal.