-
Notifications
You must be signed in to change notification settings - Fork 24
What are the difference between Equality Operator and Referential Equality Operator
Devrath edited this page Feb 29, 2024
·
2 revisions
In Kotlin, == and === are used for equality comparisons, but they serve different purposes.
-
==(Equality Operator):- The
==operator is used for structural equality, meaning it checks if the content or values of two objects are the same. - For primitive types (like numbers),
==checks for value equality. - For non-primitive types (objects),
==by default calls theequalsmethod to compare the content of the objects.
Example:
val a: Int = 5 val b: Int = 5 println(a == b) // true, because the values are the same
- The
-
===(Referential Equality Operator):- The
===operator is used for referential equality, meaning it checks if two references point to the exact same object in memory. - It is similar to the
==operator in Java for object references.
Example:
val x: Int = 10 val y: Int = 10 val z: Int = x println(x === y) // false, different memory locations println(x === z) // true, both references point to the same object
- The
-
Prints: true for integers (primitive types share the same memory)
val firstInput = 5
val secondInput = 5
println(firstInput === secondInput) // Prints: true for integers (primitive types share the same memory)- Prints: false (different objects with the same content)
val firstList = listOf(1, 2, 3)
val secondList = listOf(1, 2, 3)
println(firstList === secondList) // Prints: false (different objects with the same content)In summary:
- Use
==for checking if the content or values are the same. - Use
===for checking if two references point to the exact same object in memory.
