CodeGym /Courses /Kotlin SELF /Equality, hashCode, and toString in a data class

Equality, hashCode, and toString in a data class

Kotlin SELF
Level 33, Lesson 1
Available

1. Introduction

When you’re just starting to program, you want the code to simply “work”: enter a number → get a result. But as soon as you introduce your own models (for example, Expense in our mini expense tracker), you start comparing objects, storing them in collections, and printing them for debugging. And then it suddenly turns out that without proper equals/hashCode/toString, your program can behave like a cat pretending it doesn’t know you.

Let’s imagine our console expense-tracking program. We add expenses to a list, build reports by category, and sometimes want to prevent duplicates. What is a “duplicate”? Two objects with the same fields? Or “this is literally the exact same object”? And when we do println(expense), we want to see something readable, not a mysterious memory-level address like “an object exists somewhere, but I won’t tell you where”.

data class exists exactly for these scenarios: data models almost always need convenient printing and correct comparison. Kotlin takes care of generating the standard methods, including equals(), hashCode(), and toString().

2. Quick refresher: == and ===

Before “blaming data class for all sins,” it’s important to confidently distinguish two comparison operators. == in Kotlin is structural equality (by meaning/value), which in practice calls equals(). === is referential equality, checking that it’s the very same object (in a sense, “the same box,” not “the same contents of the boxes”). For data you typically need ==; otherwise, you’ll be comparing not meaning, but “is it the same instance”.

Let’s look at a minimal example (and at the same time stick to the future model of our app):

data class Expense(val id: Int, val title: String, val amountCents: Long)

fun main() {
    val a = Expense(1, "Coffee", 250)
    val b = Expense(1, "Coffee", 250)

    println(a == b)   // true
    println(a === b)  // false
}

The logic is: the expenses match by fields, so == is true. But these are different objects created by two constructor calls—so === is false.

3. What a data class generates and which fields participate

A very common beginner trap: “I wrote a data class—so now everything inside the object participates in comparison and printing.” No. Kotlin does it predictably: it uses only the properties (val/var) declared in the primary constructor. From these it derives equals/hashCode/toString (and more, but today we’re focusing specifically on these three).

This is convenient because the primary constructor becomes the “data passport”: whatever is listed there is considered the model’s state.

An example of “how we want it” for expense tracking:

data class Expense(
    val id: Int,
    val title: String,
    val amountCents: Long,
    val category: String
)

Such an object is convenient to compare by all four fields, convenient to print, and convenient to use in collections.

And conversely: if you move a property into the class body, it does not participate in the automatically generated equals/hashCode/toString. This is an official rule of data class: properties in the class body are excluded from generation.

4. toString() for debugging and logs

When a program doesn’t work, a developer’s first two reactions are: “why?” and “where is my println?” And this is where toString() suddenly becomes very useful: you want to see the object as a whole and in a readable way. For a data class, toString() is generated in a format like Expense(id=1, title=Coffee, amountCents=250, category=Food)—that is, it directly shows the class name and the constructor field values.

Let’s add printing an expense:

data class Expense(val id: Int, val title: String, val amountCents: Long)

fun main() {
    val e = Expense(1, "Coffee", 250)
    println(e) // Expense(id=1, title=Coffee, amountCents=250)
}

Note an important nuance: toString() is a diagnostic representation, not “pretty user output.” A user most likely wants “Coffee — $2.50,” not “Expense(amountCents=250).” So in our app we’ll use toString() as a debugging/logging tool, and for user-facing output we’ll create a separate formatting function (but without overdoing it—we’re still in a console world).

A small practical habit: when you debug business logic, printing println(expense) is like a flashlight in a dark basement. It doesn’t make the basement beautiful, but it helps you avoid falling into a pit.

5. equals() and the meaning of objects being “the same”

Data models are often compared by content. For a data class, Kotlin generates equals() so that comparison happens by the values of the primary-constructor properties.

That means a check like this becomes natural:

data class Expense(val id: Int, val title: String, val amountCents: Long)

fun main() {
    val a = Expense(1, "Coffee", 250)
    val b = Expense(1, "Coffee", 250)
    val c = Expense(2, "Coffee", 250)

    println(a == b) // true
    println(a == c) // false
}

Within our app this gives a clear meaning: if two expenses have the same fields, they are the same as data.

But there’s an important design idea here: equality is a contract of meaning. You must decide which fields truly define “sameness.” For example, if id is a unique identifier, you may decide that two expenses are equal only if their id values are equal (and the other fields are just “record data”). But if you want to detect duplicates by content, then id may get in the way. Today we won’t “break our brains” with architectural debates—we’ll just fix the key point: a data class compares by all constructor fields, so choose those fields deliberately.

6. hashCode() and why Set and Map break without it

Comparing with equals() is only half the story. In Set and Map collections, hashCode() plays a key role. For a data class, Kotlin generates the equals()/hashCode() pair consistently—so that objects that are equal by equals have the same hashCode.

Why is this so important? Because Set and Map work roughly like this: “first use the hash to find a bucket, then use equals() to confirm.” If hashCode and equals “live separate lives,” the collection will start losing elements or failing to find keys.

A very simplified lookup scheme in a HashMap looks like this:

flowchart TD
    A["Klyuch (key)"] --> B["hashCode()"]
    B --> C["korzina / bucket"]
    C --> D["equals() s kandidatami"]
    D --> E["nashli znachenie / ne nashli"]

Now let’s show the benefit in practice. Suppose we want to store expenses by id:

data class ExpenseId(val value: Int)

fun main() {
    val m = mapOf(ExpenseId(1) to "Coffee", ExpenseId(2) to "Taxi")
    println(m[ExpenseId(1)]) // Coffee
}

Why does this work? Because ExpenseId(1) is “equal” to another ExpenseId(1) by equals, and they have the same hashCode. That’s exactly why we can create a new key object and still successfully find the old value.

7. Properties in the data class body and “invisible” fields

This is a classic mistake: you add a field, expect it to participate in comparisons and printing, and it’s “as if it’s invisible.” The reason is almost always the same: the field is declared not in the primary constructor, but in the class body. Then it is excluded from equals/hashCode/toString (and from other generated functions), because Kotlin only takes constructor properties into account.

Let’s look at an example that seems reasonable but behaves unexpectedly:

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

fun main() {
    val a = User("Ann").also { it.age = 10 }
    val b = User("Ann").also { it.age = 99 }

    println(a == b) // true
    println(a)      // User(name=Ann)
}

Reading this as a human, you want to say: “but they’re different; the age is different.” But from the data class perspective, age is not part of the data because it’s not in the primary constructor. Kotlin does this intentionally and predictably: you decide what belongs in the “data passport,” and what is auxiliary state.

A practical rule for our expense-tracking app: if a field affects uniqueness, comparisons, usage in Map/Set, and generally is part of the model’s data—keep it in the primary constructor. If it’s a cache, a temporary UI flag (there is “UI” even in console apps, don’t laugh), or technical state—you can move it into the class body, but then don’t be surprised by the consequences.

8. Practice in the app: Set, Map, and key stability

Anti-duplicates and Set

In our early project versions we often stored records in a MutableList and did searching/removal manually. That’s fine to start with. But once we use classes—and especially data class—we want a bit more order: for example, prevent adding a full duplicate if the user accidentally repeats a command.

Let’s say we have a simple function to add an expense to a list, but we want to check for duplicates. For a demonstration, a Set is enough because it stores unique elements (by equals/hashCode).

data class Expense(val id: Int, val title: String, val amountCents: Long)

fun main() {
    val unique = mutableSetOf<Expense>()

    unique.add(Expense(1, "Coffee", 250))
    unique.add(Expense(1, "Coffee", 250))

    println(unique.size) // 1
}

From the Set point of view, the second element is a duplicate because it is equal to the first by equals() and has the same hashCode(). For data models, this is usually exactly what the programmer expects (and the user too: “why do I need two identical coffees at the same moment?”).

But again a design question comes up: what should be considered a duplicate—“same content” or “same id”? In a real application this depends on your logic. Today the more important point is: data class makes collection behavior predictable if you choose constructor fields correctly.

Map keys and “why can’t it find it?!”

Next practical scenario: you build an index or fast access. For example, you want to find an expense by id. While you used a List, you searched with a loop or find. But Map can access by key almost instantly—if keys are compared correctly.

Let’s show it with a small example (without complicating it with architecture):

data class Expense(val id: Int, val title: String, val amountCents: Long)

fun main() {
    val byId = mapOf(
        1 to Expense(1, "Coffee", 250),
        2 to Expense(2, "Taxi", 1500)
    )

    println(byId[2]) // Expense(id=2, title=Taxi, amountCents=1500)
}

And if we want the key to be not an Int, but our own separate type (this is often done to avoid mixing up different identifiers), then a data class is perfect:

data class ExpenseId(val value: Int)

fun main() {
    val byId = mapOf(ExpenseId(1) to "Coffee")
    println(byId[ExpenseId(1)]) // Coffee
}

And this is exactly where you again see why equals/hashCode are critical: we created a new ExpenseId(1) and still found the value. This is the basic “magic” of Map, and it works thanks to the equality contract that data class generates automatically.

Pitfall: mutable keys in Map and elements in Set

Now comes the moment when many people first understand why experienced developers love val and not var. And no, it’s not about morality. It’s about the fact that hashCode must be stable while an object sits in a HashSet or is used as a key in a HashMap.

If the fields participating in equals/hashCode can be changed (var), you can put an object into a Set, then modify it, and… the Set starts behaving strangely: the object seems to exist, but contains may return false. This is not a “Kotlin bug”; it’s a consequence: the object ended up in a bucket based on the old hash, and after modification it should belong in a new one.

A bad example (as an example only, not as something to imitate):

data class Key(var id: Int)

fun main() {
    val s = hashSetOf(Key(1))
    val k = s.first()

    k.id = 2

    println(s.contains(Key(2))) // false (very likely)
}

There’s no guarantee you’ll see the exact same result on all implementations, but the idea remains: changing key fields after putting an object into a HashSet/HashMap is like changing the apartment number on the door while the courier is already standing on the stairs. The courier (the collection) honestly came to the address, but the address “suddenly updated.”

For our app, the practical rule is simple: if an object will be an element of a Set or a key in a Map, then the fields affecting equals/hashCode are best made val and not changed. This makes the program predictable and saves hours of debugging that would otherwise be spent talking to the void: “why can’t it find the key, I just added it.”

Can you override equals/hashCode/toString manually?

Sometimes the thought comes up: “What if I need a different print format or a different notion of equality?” In Kotlin this is possible: you can write your own implementations of equals(), hashCode(), or toString() right in the body of a data class. But then the compiler won’t generate these methods for you—it will use yours. This is described as part of the generation rules for a data class: if there are explicit implementations (or final ones in a superclass), they are not generated automatically.

At the course level (and especially at the level of “I’m not very confident at programming yet”), it’s better to follow this principle: if a data class fits, use auto-generation. If it doesn’t fit, that’s a signal that the data model might be designed incorrectly, or you’re trying to use one model to solve tasks that are too different.

You may sometimes want to change toString(), but remember: we agreed that toString() is a debugging tool. If you make it “pretty for the user,” you can lose diagnostic value. A bit later, when we improve the design of domain models, you’ll learn to separate “logging/debugging” and “user output” even more carefully.

9. Common mistakes

Mistake #1: expecting fields in the data class body to participate in equality and printing.
This is one of the most common reasons for “magical behavior”: you added var age or var cachedTotal, and then you’re surprised that println(obj) doesn’t show it, and obj1 == obj2 ignores it. For a data class, auto-generation only uses primary-constructor properties, and that’s intentional so that the “data structure” is clearly visible in the class header.

Mistake #2: using === to compare data models.
Referential equality is rarely useful and usually only in special cases. For models like Expense, User, Product, you almost always want ==, because the meaning of “sameness” is the same fields, not “the same reference.” If you accidentally compare with ===, you’ll get false even for “identical” expenses and start building logic on the wrong check.

Mistake #3: making key fields var and modifying an object after adding it to a HashSet/HashMap.
This is the case where the program doesn’t just crash—it starts gaslighting you: “the element isn’t there,” even though you added it. The reason is that HashSet and HashMap rely on the stability of hashCode. If a field participating in hash computation changes, the object would “move” to a different bucket, but the collection doesn’t learn about it. That’s why for keys and unique elements, people almost always choose val.

Mistake #4: treating toString() as user output.
toString() on a data class is indeed very convenient and readable, but it is intended for diagnostics: debugging, logs, checking state. If you start showing it to the user as an “interface,” you quickly run into the fact that the format is not friendly (and can change when fields are renamed). It’s better to have a separate formatting function for display, and leave toString() for the developer—that is, for you, when you fix a bug at night and quietly promise yourself “tomorrow I’ll rewrite everything nicely.”

1
Task
Kotlin SELF, level 33, lesson 1
Locked
Order and reference
Order and reference
1
Task
Kotlin SELF, level 33, lesson 1
Locked
Point for Humans
Point for Humans
1
Task
Kotlin SELF, level 33, lesson 1
Locked
Scores in the shadows
Scores in the shadows
1
Task
Kotlin SELF, level 33, lesson 1
Locked
Passport in a map
Passport in a map
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION