Junior
What is the difference between double and triple equals in Kotlin, and why was the triple equals introduced?
sobes.tech AI
Answer from AI
-
Double equals (
==): Compares the contents of two objects (structural equality). For primitive types, it compares the value, and for objects — the result of calling theequals()method. -
Triple equals (
===): Compares references to objects in memory (referential equality). Returnstrueif both variables refer to the same instance of an object.
Triple equals was introduced for explicit comparison of object references, which is important for determining whether two variables point to the same object in memory, rather than just objects with the same content.
// example comparison
val string1 = "hello"
val string2 = "hello"
val string3 = String("hello".toCharArray()) // New object
println(string1 == string2) // true (contents are the same)
println(string1 == string3) // true (contents are the same)
println(string1 === string2) // true (Kotlin optimizes strings - same object for identical literals)
println(string1 === string3) // false (different objects in memory)
println(string2 === string3) // false (different objects in memory)