Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Kotlin
Stage 5: Specialization

Part 09 / Topic 5 of 10

Data classes: what copy() and friends actually generate

Part 7 wrote a class's equals, if it needed one, by hand. Here's what that looks like, so data class reads as "the compiler writing this for me" rather than "a struct keyword with no context":

class ManualOrder(val orderId: String, val itemCount: Int, val totalInr: Double) {
    override fun equals(other: Any?): Boolean {
        if (this === other) return true
        if (other !is ManualOrder) return false
        return orderId == other.orderId && itemCount == other.itemCount && totalInr == other.totalInr
    }
    override fun hashCode(): Int {
        var result = orderId.hashCode()
        result = 31 * result + itemCount
        result = 31 * result + totalInr.hashCode()
        return result
    }
    override fun toString(): String = "ManualOrder(orderId='$orderId', itemCount=$itemCount, totalInr=$totalInr)"
}

data class Order(val orderId: String, val itemCount: Int, val totalInr: Double)
Manual toString: ManualOrder(orderId='ORD-1001', itemCount=3, totalInr=1450.0)
Manual equals: true, same reference: false
Manual hashCode equal too: true

Data class toString (generated): Order(orderId=ORD-1001, itemCount=3, totalInr=1450.0)
Data class equals: true, same reference: false
After copy(totalInr = 1305.0): Order(orderId=ORD-1001, itemCount=3, totalInr=1305.0)
Original unchanged: Order(orderId=ORD-1001, itemCount=3, totalInr=1450.0)
Destructured: id=ORD-1001, count=3, total=1450.0
Distinct orders in a set: 2

copy(totalInr = 1305.0) builds a new Order with every property kept except the one named — the original is never mutated. val (id, count, total) = orderA destructures using the generated component1()/component2()/component3() functions, in constructor order. Both orderA and discounted land as 2 distinct entries in a Set, because equals/hashCode were generated consistently — exactly the pairing ManualOrder had to get right by hand above.

Full program: examples/04_data_classes.kt.

Done here? The practice set for Part 9 — including the solutions — is on the part page.

Search the guide