Kotlin == vs ===: Key Differences and Usage Explained
== 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 | == | === |
|---|---|---|
| Purpose | Checks structural equality (value equality) | Checks referential equality (same object) |
| Underlying mechanism | Calls equals() method | Compares memory references directly |
| Null safety | Safe to use with nulls (calls equals() safely) | Safe to use with nulls (compares references) |
| Typical use case | Compare content of objects | Check if two variables point to the same instance |
| Overridable | Yes, 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.
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 }
=== Equivalent
This code shows how === checks if two variables point to the same object.
fun main() {
val a = "hello"
val b = "hello"
val c = a
println(a === b) // true due to string interning
println(a === c) // 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.== for value equality and === for identity checks.null values.equals() to customize == behavior for your classes.