Understanding the Difference Between == and === in Kotlin

Puneet Grover
2 min readMay 5, 2023

In Kotlin, there are two ways to compare two values: using the == operator and the === operator. Although both operators are used for comparison, they work differently and are used in different scenarios.

The == operator is used to compare the values of two objects for equality. It checks if the values of the two objects are the same or not, but it does not compare the references of the objects. On the other hand, the === operator is used to compare the references of two objects. It checks if the two objects refer to the same memory location in the heap or not.

Example:-

Let’s look at an example to understand this better:

val str1: String = "Hello"
val str2: String = "Hello"
val str3: String? = str1

// Using ==
println(str1 == str2) // true
println(str1 == str3) // true

// Using ===
println(str1 === str2) // false
println(str1 === str3) // true

In this example, we declare three variables str1, str2, and str3. str1 and str2 contain the same string value, while str3 refers to the same object as str1.

When we use == to compare str1 and str2, we get true because the values of the two strings are the same. When we use == to compare str1 and str3, we also get true because the values of the two strings are the same.

However, when we use === to compare str1 and str2, we get false because str1 and str2 are two different objects, even though they have the same value. When we use === to compare str1 and str3, we get true because str3 refers to the same object as str1.

To summarize, use == to compare the values of two objects, and use === to compare the references of two objects. Understanding the difference between these two operators can help you write more accurate and effective code in Kotlin.

I hope this article helps you understand the difference between == and === in Kotlin.

Watch Video ▶️ On My Youtube Channel “CodingWithPuneet”

Like | Share | Subscribe for more such Relatable Content.

Keep Learning, Happy Coding!

--

--

Puneet Grover

Android Team Lead (Senior Consultant) @Deloitte USI | Google Certified Android Dev | Java | Kotlin | Blogger | Sometimes Youtuber