0
0
Kotlinprogramming~5 mins

Equality (== structural vs === referential) in Kotlin

Choose your learning style9 modes available
Introduction

We use equality to check if two things are the same. Kotlin has two ways: == checks if the content is the same, and === checks if they are the exact same object.

When you want to see if two strings have the same letters.
When you want to check if two variables point to the exact same object in memory.
When comparing simple data like numbers or data classes for equality.
When you want to avoid bugs caused by confusing content equality with object identity.
Syntax
Kotlin
a == b  // checks if a and b have the same content (structural equality)
a === b // checks if a and b are the same object (referential equality)

== calls equals() under the hood, so it compares content.

=== checks if both variables point to the same place in memory.

Examples
Here, == is true because the text is the same. === may be true or false because they might be different objects.
Kotlin
val x = "hello"
val y = "hello"
println(x == y)  // true
println(x === y) // might be true or false depending on string interning
a and b point to the same object, so === is true. c is a different object.
Kotlin
val a = Any()
val b = a
val c = Any()
println(a === b) // true
println(a === c) // false
Data classes have equals() that checks content, so == is true. But they are different objects, so === is false.
Kotlin
data class Person(val name: String)

val p1 = Person("Alice")
val p2 = Person("Alice")
println(p1 == p2)  // true
println(p1 === p2) // false
Sample Program

This program shows the difference between == and === with data class objects.

Kotlin
data class Book(val title: String)

fun main() {
    val book1 = Book("Kotlin Guide")
    val book2 = Book("Kotlin Guide")
    val book3 = book1

    println(book1 == book2)  // structural equality
    println(book1 === book2) // referential equality
    println(book1 === book3) // referential equality
}
OutputSuccess
Important Notes

Use == most of the time to compare values.

Use === when you want to check if two variables are exactly the same object.

Data classes automatically provide good equals() behavior for ==.

Summary

== checks if two things have the same content (structural equality).

=== checks if two things are the exact same object (referential equality).

Remember: == is for value comparison, === is for identity comparison.