We often need to compare the data of two variables or objects or the references of two objects in Kotlin. This brings in another question, which equality check should we use in which case.
This post was originally posted at https://agrawalsuneet.github.io/blogs/equality-in-kotlin/ and reposted on Medium on 05th Sept 2018.
Let’s figure out what are the types of checks available in Kotlin.
Structural Equality (‘==’)
== operator is used to compare the data of two variables.
Please don’t misunderstand this equality operator with the Java
== operator as both are different.
== operator in Kotlin only compares the data or variables, whereas in Java or other languages
== is generally used to compare the references. The negated counterpart of
== in Kotlin is
!= which is used to compare if both the values are not equal to each other.
Referential equality (‘===’)
=== operator is used to compare the reference of two variable or object. It will only be
true if both the objects or variables pointing to the same object. The negated counterpart of
=== in Kotlin is
!== which is used to compare if both the values are not equal to each other. For values which are represented as primitive types at runtime (for example, Int), the
=== equality check is equivalent to the