CodeGym /Courses /Kotlin SELF /== vs === and the “value vs reference” model

== vs === and the “value vs reference” model

Kotlin SELF
Level 23, Lesson 0
Available

1. Two kinds of equality: “same meaning” and “the exact same object”

When you write programs, you constantly compare things. Sometimes you compare “by meaning”: for example, the two strings "cat" and "cat" are the same word. And sometimes you care about a different question: “is this literally the same thing, or two different things that just look alike?”.

It’s like keys: two keys can be cut the same way (==), but one is the original and the other is a copy, and that matters in some situations (===).

In Kotlin these two comparison tasks are separated at the language level, so you can explicitly say what exactly you want to check. This is especially useful with collections, because collections are “container-like”: they can be the same by content, but be different containers, or the other way around—one container can have “two names” in code.

== — structural equality

The == operator in Kotlin means structural equality. In normal human terms this is “equal by value/content”, i.e., “whatever matters for the meaning matches”.

Technically, Kotlin reduces a == b to a call to equals, but does it carefully: comparison with null is safe, and separate checks like “what if a is null” are usually unnecessary.

It’s important to memorize this idea right away: == is your “workhorse” comparison operator that you will use almost always—when checking computation results, searching for an element in a collection, comparing strings, numbers, etc.

Mini-table: what == usually means for different types

Type What == means (intuitively)
Int, Double, Char, Boolean
whether the values are equal (number, character, fact)
String
whether the text is identical character by character
List
whether the size is the same and all elements are equal in the same order (order matters)
Pair/Triple
whether all components are equal

For lists this is especially important: two lists with the same elements but in different order are usually considered not equal (because order is part of the meaning of a list).

Example: == on strings and numbers

fun main() {
    val a = "hi"
    val b = "hi"
    val x = 10
    val y = 10

    println(a == b) // true
    println(x == y) // true
}

This is exactly the behavior you expect.

Example: == is safe with null

Kotlin has a nice feature: == “understands” null and does not crash.

fun main() {
    val x: String? = null
    val y: String? = "hi"

    println(x == null) // true
    println(y == null) // false
    println(x == y)    // false
}

Notice the last println(x == y): there is no risk of “bringing the program down” by dereferencing null. == is safe, which makes the code simpler and cleaner.

2. === and shared references (aliasing)

=== — referential equality

The === operator answers a different question: “do these two variables point to the same object?”. In conversational terms: “is this one container or two?”. This is not “better” or “worse” than ==—it’s just a different meaning. If == is about value, then === is about identity.

In everyday application code, === is rare. But for debugging, for checking “did we accidentally copy a reference?”, and for diagnosing weird collection behavior—it’s useful.

Example: two identical collections are not the same object

fun main() {
    val a = mutableListOf(1, 2, 3)
    val b = mutableListOf(1, 2, 3)

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

The content is the same, so a == b yields true. But these are two different lists, so a === b yields false.

Example: a “second name” for the same list

fun main() {
    val a = mutableListOf("x")
    val b = a

    b.add("y")

    println(a)       // [x, y]
    println(b)       // [x, y]
    println(a === b) // true
}

This is the main source of “magic” in a beginner’s eyes: you added an element through b, and a changed. Because a and b are two names for the same container.

What is aliasing and why it’s confusing

A situation where two variables refer to the same object is called aliasing (you can think of it as “a pseudonym” or “a second name”). For beginners, aliasing can feel like the language “has a life of its own”, but in reality everything is logical: you’re simply holding one container in two variables, not two containers.

It’s very useful to visualize this in your head as arrows: a variable is a “label” that points to a real object. Two labels can point to one object, and then changes through one label are visible through the other.

Let’s draw a simple diagram:

flowchart LR
    A[a: MutableList] --> L[(List)]
    B[b: MutableList] --> L

That’s why in Kotlin it’s so important to distinguish “value” and “reference”, even if we don’t dive into how JVM memory works. At the everyday-logic level, it’s enough to remember: a mutable collection can have multiple “names”, and then changes are shared.

Mini-example from the course topic: a simple CLI app

Imagine we’re building the simplest expense tracker (no classes yet, only Pair), and we store operations as pairs "category" to amount.

fun main() {
    val expenses = mutableListOf("food" to 250, "taxi" to 120)

    val visibleExpenses = expenses  // "pretended this is a copy"
    visibleExpenses.add("books" to 90)

    println(expenses)        // [(food, 250), (taxi, 120), (books, 90)]
    println(visibleExpenses) // [(food, 250), (taxi, 120), (books, 90)]
}

If you expected visibleExpenses to be “a separate list for display”, you’ve just introduced a bug: you changed the “view”, and the “data” changed.

3. val does not make an object immutable

A very common confusion looks like this: “But I used val, so it can’t change”. But val means only one thing: the variable cannot point to a different object. However, if the object itself is mutable (for example, MutableList), you can still change its contents.

Example: val + MutableList still changes

fun main() {
    val numbers = mutableListOf("one", "two")
    numbers.add("three")

    println(numbers) // [one, two, three]
}

And that’s normal. val here protects you from accidentally reassigning the variable (i.e., you won’t be able to do numbers = mutableListOf(...)), but it does not forbid changing the list’s contents.

Why this is good

If val forbade changing the internals of a mutable object, you’d need a separate language construct for “hard immutability”. Kotlin keeps it simpler: val is about the variable; mutability is about the object/type itself.

So a good project habit is: use val by default, and enable mutability only where you really need it. This reduces the number of unexpected “reference swapping” situations in code.

4. A trap: === on nullable numbers

Sometimes, after learning about ===, a beginner starts using it “for reliability”. And that’s where a small tragicomedy happens. For types like String, List, Map, === can sometimes be useful, but on nullable numbers (Int?, Double?) you will almost certainly get behavior that looks like a bug.

We won’t go deep into “how it’s stored in memory”, but the practical rule is simple: if you have Int?, then === checks not the value, but “is this exactly the same wrapper object or not”, and the answer will often be false, even when the numbers are equal.

fun main() {
    val a: Int? = 1000
    val b: Int? = 1000

    println(a == b)   // true
    println(a === b)  // often false (and that's normal)
}

Life takeaway: compare numbers with ==. === does not add “reliability”; it changes the meaning of the check, and you dig a hole for yourself, then heroically climb out of it.

5. Practical rules and safe techniques

When you read or write Kotlin code, it’s useful to keep a simple heuristic in mind. In typical business logic you care about values: “is the command the same?”, “does the category match?”, “is the amount equal?”. All of that is about ==.

The === operator is a tool that you usually need not for application logic, but to understand “is this the same container?” or “why are changes leaking here?”.

If you want it really short: == is “equal by meaning”, === is “the same object”.

How to avoid the “shared reference” bug in a practical app

In our simple CLI expense tracker we might run into this situation: we want to “prepare a list for output”, but accidentally take the same list and start mutating it (for example, temporarily filtering, temporarily removing, temporarily adding test items).

To avoid self-sabotage, it’s convenient to adopt a rule: if you’re doing temporary processing, work with a copy.

A function to create a “snapshot” of the expense list

fun snapshotExpenses(expenses: List<Pair<String, Int>>): List<Pair<String, Int>> {
    // toList() creates a new list that can be safely displayed/processed separately
    return expenses.toList()
}

And use it:

fun main() {
    val expenses = mutableListOf("food" to 250, "taxi" to 120)

    val snapshot = snapshotExpenses(expenses)
    expenses.add("books" to 90)

    println(snapshot) // [(food, 250), (taxi, 120)]
    println(expenses) // [(food, 250), (taxi, 120), (books, 90)]
}

What matters here is that snapshot is a separate list. Even if the original list changes, the “snapshot” stays the same. This is useful when you want to show something stable to the user while the data continues to evolve.

Debugging trick: check === to catch aliasing

Sometimes you suspect that “somewhere, one collection got two names”. In that case, === is your flashlight.

fun main() {
    val expenses = mutableListOf("food" to 250)
    val sameRef = expenses
    val copy = expenses.toMutableList()

    println(expenses === sameRef) // true
    println(expenses === copy)    // false
}

This check should almost never be part of business logic, but as a diagnostic it’s excellent.

6. Common mistakes

Mistake #1: using === instead of == “just in case”.
It’s tempting with good intentions: “well, === is stricter, so it must be more reliable”. But === is not “stricter”; it’s about something else. You start comparing not values, but object identity, and suddenly “identical” strings/numbers/computation results become “not equal”. The right habit: default to ==, and use === only when you truly want to check “the same object”.

Mistake #2: being surprised that mutating a list through one variable is visible through another.
This is not mysticism and not “Kotlin broke”. This is aliasing: you assigned b = a, and now b is the second name of the same collection. The cure here is not to “ban assignments”, but to consciously distinguish between “I want a reference to the same container” and “I want a copy of the container”.

Mistake #3: thinking that val makes a collection immutable.
val forbids reassigning the variable, but does not forbid changing the contents of a mutable collection. This is a normal and useful design: you protect the reference, but don’t prevent working with the data structure.

Mistake #4: checking null via complex constructs instead of a simple x == null.
Sometimes after learning null-safety you want to write “three-story” checks: if (...) { ... } else { ... }, even when you just need to know whether it’s null or not. == in Kotlin is safe for null, so x == null is readable and perfectly fine.

Mistake #5: dragging === into application logic (command conditions, filters, “already has such an element” checks).
Even if the code “works on your tests”, it will often be logically wrong: you’re comparing not meaning, but container identity. As soon as the data starts coming from somewhere else (a new list, a new object, a different string construction), behavior becomes weird. Meaning-based checks should use ==.

1
Task
Kotlin SELF, level 23, lesson 0
Locked
Two lists to compare
Two lists to compare
1
Task
Kotlin SELF, level 23, lesson 0
Locked
A second name for the list
A second name for the list
1
Task
Kotlin SELF, level 23, lesson 0
Locked
Val and a reference
Val and a reference
1
Task
Kotlin SELF, level 23, lesson 0
Locked
Expenses snapshot
Expenses snapshot
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION