The Analogy: A Locksmith's Key-Cutting Shop
Behind the counter of a locksmith's shop stands a key-cutting machine: a vice that grips a fresh blank on one jaw and the customer's original on the other, with a tracing finger that rides along the cuts of the original while a spinning wheel grinds the same pattern of notches into the blank. The identity of a key -- which lock it will turn -- is nothing more than the depths and spacing of those notches, the pattern the trade calls the bitting. Two keys with the same bitting are, for every purpose that matters, the same key: they open the same door, and the machine cannot tell them apart. The alloy they were cut from, the afternoon they were ground, the customer who paid for them -- none of that reaches the lock. Only the profile of the metal does.
Duplicating a key is a single pull of a lever. The locksmith clamps the original, clamps a blank beside it, and the tracer copies every cut across in one pass; a minute later a second key drops into the tray, indistinguishable from the first. Now and then a customer wants a key that is almost the same -- the same blade, but one notch cut a shade deeper to suit a re-pinned lock. The locksmith traces the original for every cut except that one, which is dialled by hand. The new key shares all of the old key's bittings but the one that changed, and everything the shop knows about a key follows from the finished pattern in front of it, not from the original it was traced against.
Customers like to tie a paper tag through the bow of each key -- FRONT, CELLAR, SHED -- so they can tell one from another in a pocket. The shop keeps its own record too: a pegboard where duplicates hang in slots arranged by bitting, so that when someone returns for a third copy the locksmith reaches straight to the right peg. But the tracer, the grinding wheel and the lock itself never read the tag. Tie any words you like to the bow; the machine grips the blade, copies the notches, and the lock lifts its pins to the notches alone. The tag is a convenience for the human holding the key, invisible to every piece of steel that acts on it.
The trouble comes the day a customer leans on those tags to keep two keys apart when the metal does not. Suppose the front door and the garage were, by an oversight, cut to the same bitting. The tags read FRONT and GARAGE, so the customer treats them as two different keys; but the pegboard, organised by bitting, files them in one slot, and the lock on either door opens for both. The distinction the customer trusts lives only on the paper tag, and the paper tag is exactly the part no machine consults. The instant identity actually matters -- filing, matching, opening -- the shop honours the metal and forgets the label, and the label was where the customer had put the meaning.
Syntax or Core Structure
A Kotlin data class is the software counterpart of that key: you declare which fields make up its identity, and the compiler grinds out the machinery that compares, copies, prints and unpacks a value from exactly those fields. You mark the class with the data keyword and give it a primary constructor whose parameters are all val or var.
data class Key(val profile: String, val bittings: String)
fun main() {
val a = Key("Yale", "35142")
val b = Key("Yale", "35142")
val c = a.copy(bittings = "35148")
println(a)
println(a == b)
println(a === b)
println(c)
println(a == c)
println(a.hashCode() == b.hashCode())
}
Output:
Key(profile=Yale, bittings=35142)
true
false
Key(profile=Yale, bittings=35148)
false
true
Here a and b are two blanks cut to the same pattern. The expression a == b calls the generated equals, which compares profile and bittings, so it is true; a === b asks whether they are the very same object in memory, which is false. The value c is a duplicate of a with one cut changed through copy, so a == c is false. Equal objects are required to return equal hash codes, and the last line confirms they do.
Technical Depth: What the Compiler Grinds Out
The six generated members
The data keyword instructs the compiler to synthesise a fixed set of members from the properties declared in the primary constructor. You write the pattern once; the machinery follows.
| Member | What it does | Derived from |
|---|---|---|
equals | structural comparison with == | primary-constructor properties |
hashCode | bucket value for hash-based collections | primary-constructor properties |
toString | readable form like Key(profile=Yale, ...) | primary-constructor properties |
component1, component2, ... | one accessor per property, for destructuring | primary-constructor properties, in order |
copy | a new instance with selected fields replaced | primary-constructor properties |
Every one of these reads the same source: the properties in the primary constructor, in the order you wrote them. That single fact drives every surprise in this lesson.
Body properties are invisible to all of it
A property you declare inside the class body, rather than in the primary constructor, is a perfectly real property -- you can read it and write it -- but it takes no part in equality, hashing, string form, or destructuring. It is the paper tag on the key: present, legible, and ignored by every machine.
data class Ticket(val queue: String, val number: Int) {
var note: String = ""
}
fun main() {
val first = Ticket("returns", 12).apply { note = "urgent" }
val second = Ticket("returns", 12).apply { note = "routine" }
println(first == second)
println(first)
println(second.note)
}
Output:
true
Ticket(queue=returns, number=12)
routine
The two tickets carry different notes, yet first == second is true, because note lives in the body and equals never looks at it. The generated toString omits note for the same reason: the printed form shows only queue and number. The note is still there -- second.note prints routine -- but it is metadata for you, not identity for the compiler.
Destructuring reads by position, not by name
The componentN functions let you unpack a value into several names at once. The binding is positional: the first name receives component1, the second component2, regardless of what you call them.
data class Point(val x: Int, val y: Int)
fun main() {
val p = Point(3, 7)
val (x, y) = p
val (across, up) = p
println("x=$x y=$y")
println("across=$across up=$up")
}
Output:
x=3 y=7
across=3 up=7
The names across and up receive the same values as x and y, because destructuring cares only about order. If you ever reorder the primary constructor, every positional destructuring in the codebase silently changes meaning while continuing to compile -- a real hazard the name-blindness creates.
copy is shallow
The generated copy builds a new object, but it copies each property by assignment -- for a reference type that means the reference, not the thing it points at. Trace a duplicate whose original holds a mutable list is to see the two share one list.
data class Cart(val owner: String, val items: MutableList<String>)
fun main() {
val original = Cart("anya", mutableListOf("rope", "chalk"))
val clone = original.copy()
clone.items.add("torch")
println(original.items)
println(clone.items)
println(original.items === clone.items)
}
Output:
[rope, chalk, torch]
[rope, chalk, torch]
true
Adding torch to the clone's list changes the original's list too, and === confirms both carts point at one and the same list object. copy traced the reference across, exactly as the key machine would trace one blank from another; it did not manufacture a fresh list. When a data class holds mutable state, a shallow copy shares that state, and you must copy the inner collection yourself if you want independence.
Technical Depth: Sealed Classes
A closed set of shapes
A sealed class defines a type whose direct subtypes are all known to the compiler, because they must be declared in the same module (and, for a sealed class, the same package). It is the pegboard of blank types the shop stocks: a fixed range, nothing arriving unannounced from another supplier.
sealed class CutResult
data class Success(val bittings: String) : CutResult()
data class Rejected(val reason: String) : CutResult()
object OutOfBlanks : CutResult()
fun describe(r: CutResult): String = when (r) {
is Success -> "cut " + r.bittings
is Rejected -> "refused: " + r.reason
OutOfBlanks -> "no blanks left"
}
fun main() {
println(describe(Success("35142")))
println(describe(Rejected("worn original")))
println(describe(OutOfBlanks))
}
Output:
cut 35142
refused: worn original
no blanks left
The when has no else branch, and it compiles anyway. Because the compiler knows the three subtypes are the whole family, it can prove the when is exhaustive. The payoff arrives the day someone adds a fourth subtype: every when over CutResult that lacks the new case stops compiling, pointing you at each place that must decide what the new shape means. An else branch would have swallowed the new case silently.
Sealed against the alternatives
| Feature | enum class | sealed class | open class |
|---|---|---|---|
| fixed set of cases | yes | yes | no |
| different data per case | no (one shape) | yes (each subtype differs) | yes |
exhaustive when with no else | yes | yes | no |
| new subtypes from another module | no | no | yes |
| multiple instances per case | no (one each) | yes | yes |
An enum gives a closed set but forces every case into one shape. An open class lets each subtype carry its own data but can be extended anywhere, so when can never be exhaustive. A sealed class takes the closed set from the enum and the per-case data from the open class, which is why it is the natural way to model a fixed list of outcomes that each carry different information.
Real World Example: A Key Register at the Cutting Bench
The shop keeps a register of every key it has issued, so it can answer "have we cut this before?" and spot two keys that clash. Each job at the bench is one of a fixed set: a fresh cut with a customer label, a recut of a key already on file, or the end-of-shift close. That fixed set is a sealed class, and the register is a set of key identities.
data class KeyId(val profile: String, val bittings: String) {
var label: String = ""
}
sealed class CutJob
data class Cut(val profile: String, val bittings: String, val label: String) : CutJob()
data class Recut(val profile: String, val bittings: String) : CutJob()
object ShopClosed : CutJob()
fun main() {
val jobs: List<CutJob> = listOf(
Cut("Yale", "35142", "front door"),
Cut("Yale", "77310", "cellar"),
Cut("Chubb", "58204", "office"),
Cut("Yale", "35142", "garage"),
Recut("Yale", "77310"),
ShopClosed
)
val issued = LinkedHashSet<KeyId>()
val collisions = mutableListOf<String>()
var cuts = 0
var recuts = 0
var closed = 0
for (job in jobs) {
when (job) {
is Cut -> {
cuts++
val id = KeyId(job.profile, job.bittings).apply { label = job.label }
val added = issued.add(id)
if (!added) collisions.add(job.label + " / " + job.bittings)
}
is Recut -> {
recuts++
val probe = KeyId(job.profile, job.bittings)
println("recut " + job.bittings + " on file: " + issued.contains(probe))
}
ShopClosed -> closed++
}
}
println("jobs seen: " + jobs.size)
println("cuts: " + cuts)
println("recuts: " + recuts)
println("closed: " + closed)
println("distinct keys: " + issued.size)
println("collisions: " + collisions)
for (k in issued) {
println(k.profile + " " + k.bittings + " -> " + k.label)
}
}
Output:
recut 77310 on file: true
jobs seen: 6
cuts: 4
recuts: 1
closed: 1
distinct keys: 3
collisions: [garage / 35142]
Yale 35142 -> front door
Yale 77310 -> cellar
Chubb 58204 -> office
The model is compact. CutJob is a sealed class with three subtypes, so the when in the loop is exhaustive with no else, and each branch reads only the fields its subtype owns: Cut carries a label, Recut does not, ShopClosed carries nothing. The register is a LinkedHashSet<KeyId>, which preserves insertion order and uses the data class's generated equals and hashCode to decide membership. That is the whole engine: dispatch on the job's shape, and let the set's identity rules do the matching.
The recut line prints during the loop, before the summary. At job five the shop wants a second copy of the cellar key, so it builds a KeyId("Yale", "77310") with no label and asks issued.contains(probe); the answer is true because equals compares profile and bittings and ignores the missing label, exactly as intended for a "have we cut this?" check. The stored key has label cellar, the probe has none, and they still match on metal.
The summary then reports six jobs, of which four were cuts, yet only three distinct keys landed in the register. The fourth cut collided: the collisions line names garage / 35142. When issued.add was called for the garage key, it found a KeyId already present with the same profile and bittings, returned false, and left the set unchanged. The final three lines list the register in insertion order, and the Yale 35142 slot still reads front door -- the label from the first cut, not the garage that followed.
That last detail is the real design flaw, and it is worth stating plainly. KeyId builds its identity from profile and bittings only; label is a body property, so the generated equals and hashCode never see it. The front door and the garage were cut to the same bitting, so as far as the register can tell they are one key, and LinkedHashSet.add keeps the element already present rather than replacing it -- the first label wins, and garage is dropped from the register entirely. The program flags the collision but cannot resolve it, because the field that would distinguish the two doors is precisely the field identity omits. There is a second, quieter hazard in the same class: label is a var, and had an identity field like bittings been a var mutated after insertion, the key's hash would shift and the object would become unfindable in its own set. Both faults trace to one decision -- putting meaning in a field the identity machinery does not read.
Common Mistakes
- Expecting body properties to count toward identity. A property declared in the class body, not the primary constructor, is ignored by
equals,hashCode,toString,componentNandcopy. Two instances that differ only in a body property compare equal, which is the fault behind the dropped garage key above.
- Assuming
copyis deep.copyduplicates each property by reference. If a data class holds aMutableListor another mutable object, the copy shares it, and mutating one side changes the other. Copy the inner collection yourself when you need independence.
- Mutating an identity field after storing the object. If an equality-defining property is a
varand you change it while the object sits in aHashSetor is aHashMapkey, its hash no longer matches its bucket and the object becomes unreachable. Keep identity fieldsval.
- Confusing
==with===. In Kotlin==callsequals(structural), and===tests reference identity. Two distinct data-class instances with equal fields are==but not===; reaching for===to compare values is a common slip for those arriving from other languages.
- Adding an
elseto awhenover a sealed type. Theelsebranch makes thewhencompile no matter how many subtypes exist, which throws away the compiler's exhaustiveness check. Add a new subtype later and nothing warns you that thiswhennever handles it.
- Relying on destructuring names.
val (a, b) = pointbinds by position, not by the property names. Reorder the primary constructor and every destructuring across the codebase quietly changes meaning while still compiling.
- Trying to write a data class with no primary-constructor properties. A data class must have at least one parameter in its primary constructor, and every parameter must be
valorvar. An empty or parameterless data class does not compile.
- Overriding one of
equals/hashCodeby hand and not the other. If you replace the generatedequalsbut leavehashCode, or the reverse, you break the contract that equal objects share a hash code, and hash-based collections start losing entries.
- Treating
copyas a way to deep-edit nested data.user.copy(address = user.address.copy(city = "Leeds"))works only if you copy at every level by hand. A singlecopyat the top leaves every nested object shared with the original.
Best Practices
- Put exactly the identity-defining fields in the primary constructor, and keep everything else -- caches, notes, derived values -- in the body where the generated members will ignore it.
- Make primary-constructor properties
val. Immutable identity fields keep an object's hash stable for the whole time it lives in a set or map.
- Prefer
copyover rebuilding an object by hand when you need a near-identical value; it names only the fields that change and leaves the rest exactly as they were.
- When a data class holds a mutable collection, copy that collection explicitly inside or after
copy, or store an immutableListinstead of aMutableListso sharing cannot bite.
- Model a fixed set of alternatives that each carry different data as a sealed class, so
whenover it stays exhaustive and adding a case forces every handler to be revisited.
- Let
whenbe an expression when it is over a sealed type; used as an expression it must be exhaustive, so the compiler enforces the check rather than trusting you to remember.
- Reach for destructuring only on small records whose field order is obvious at a glance, such as a coordinate or a map entry, and read fields by name everywhere else.
- Pair a sealed class with data-class subtypes for the cases that carry a payload and an
objectfor the cases that do not, giving each shape exactly the fields it needs.
Practice Exercises
- Declare
data class Coin(val value: Int, val year: Int)with a body propertyvar mintNote: String. Create two coins with equalvalueandyearbut differentmintNote, add both to aHashSet, and print the set's size. Explain why the note did not keep them apart.
- Build
data class Basket(val id: Int, val items: MutableList<String>). Make acopy, add an item to the copy'sitems, and print both baskets. Then change the class so the copy gets its own independent list, and show the difference.
- Model a parking gate outcome as
sealed class GateResultwithdata class Opened(val plate: String),data class Denied(val reason: String), andobject Maintenance. Write an exhaustivewhenwith noelsethat returns a message for each, then add a fourth subtype and observe whichwhenexpressions stop compiling.
- Redesign the
KeyIdregister so two doors that share a bitting are tracked as distinct keys. Decide which fields belong in the primary constructor, movelabelinto identity if it must distinguish keys, and show that the garage key is no longer dropped.