0
0
Kotlinprogramming~3 mins

Equality (== structural vs === referential) in Kotlin - When to Use Which

Choose your learning style9 modes available
The Big Idea

Ever wondered why two things that look the same might still be different in your program?

The Scenario

Imagine you have two boxes with the same toys inside. You want to check if the boxes are the same. Manually, you might look inside each box and compare every toy one by one.

The Problem

This manual checking is slow and easy to mess up. Sometimes you might think two boxes are different just because they are different boxes, even if the toys inside are exactly the same. Or you might miss a toy and say they are the same when they are not.

The Solution

Kotlin gives you two ways to compare: == checks if the contents (toys) are the same, and === checks if the boxes themselves are the exact same box. This makes comparing clear and easy.

Before vs After
Before
if (box1 === box2) { println("Same box") } else { println("Different boxes") }
After
if (box1 == box2) { println("Boxes have same toys") } else { println("Boxes have different toys") }
What It Enables

This lets you quickly and correctly check if two things are truly equal in content or just the same object, avoiding confusion and bugs.

Real Life Example

When checking if two user profiles have the same information, you want to compare their details (==), not if they are the exact same profile object in memory (===).

Key Takeaways

== checks if contents are equal (structural equality).

=== checks if two references point to the same object (referential equality).

Using the right equality avoids mistakes and makes your code clearer.