0
0
KotlinComparisonBeginner · 3 min read

Kotlin == vs ===: Key Differences and Usage Explained

In Kotlin, == checks if two objects are structurally equal by calling their equals() method, while === checks if two references point to the exact same object in memory. Use == for value equality and === for reference identity.
⚖️

Quick Comparison

This table summarizes the main differences between == and === in Kotlin.

Aspect=====
PurposeChecks structural equality (value equality)Checks referential equality (same object)
Underlying mechanismCalls equals() methodCompares memory references directly
Null safetySafe to use with nulls (calls equals() safely)Safe to use with nulls (compares references)
Typical use caseCompare content of objectsCheck if two variables point to the same instance
OverridableYes, by overriding equals()No, identity check is fixed
⚖️

Key Differences

The == operator in Kotlin is used to check if two objects have the same value or content. It internally calls the equals() method of the objects, which can be overridden to define what equality means for that class. This means two different objects can be == equal if their contents match.

On the other hand, === checks if two references point to the exact same object in memory. It does not consider the content but the identity of the object. This is useful when you want to know if two variables are literally the same instance.

Both operators handle null safely. Using == with null calls equals() safely without throwing exceptions, and === compares references including null references.

⚖️

Code Comparison

Here is an example showing how == works by comparing values.

kotlin
data class Person(val name: String, val age: Int)

fun main() {
    val person1 = Person("Alice", 30)
    val person2 = Person("Alice", 30)
    val person3 = person1

    println(person1 == person2)  // true, same content
    println(person1 === person2) // false, different objects
    println(person1 === person3) // true, same object
}
Output
true false true
↔️

=== Equivalent

This code shows how === checks if two variables point to the same object.

kotlin
fun main() {
    val a = "hello"
    val b = "hello"
    val c = a

    println(a === b) // true due to string interning
    println(a === c) // true
}
Output
true true
🎯

When to Use Which

Choose == when you want to compare the actual content or value of two objects, like checking if two strings or data objects represent the same data.

Choose === when you need to know if two variables refer to the exact same object instance, such as when managing object identity or caching.

Key Takeaways

== checks if two objects have equal content by calling equals().
=== checks if two references point to the same object in memory.
Use == for value equality and === for identity checks.
Both operators safely handle null values.
Override equals() to customize == behavior for your classes.