Equality checks in Kotlin (Difference between "==" and "===" Operators)

Kotlin Mobile DevelopmentApps/Applications

Kotlin is statistically typed language and it is hundred percent comparable with Java, as it was developed based on JVM. In Kotlin, there are two types of equality checks −

  • One is denoted by "==" and

  • The other one is denoted by "===".

As per the official documentation, "==" is used for structural equality, whereas "===" is used for referential equality.

For any expression,

  • a==b will evaluate to True only when the value of both "a" and "b" are equal.

  • a===b will evaluate to True only when both "a" and "b" are pointing to the same object.

Example – Equality in Kotlin

In this example, we will demonstrate how these two operators ("==" and "===") work.

fun main(args: Array<String>) {
   val student1 = "Ram"
   val student2 = "shyam"
   val student4 = "Ram"

   val student3=student1

   // prints true as both pointing to the same object
   println(student1 === student3)

   // prints false
   println(student1 === student2)

   //prints true
   println(student1 == student4)
}

Output

On execution, it will produce the following output −

true
false
true
raja
Updated on 01-Mar-2022 11:16:42

Advertisements