0
0
Kotlinprogramming~10 mins

Equality (== structural vs === referential) in Kotlin - Visual Side-by-Side Comparison

Choose your learning style9 modes available
Concept Flow - Equality (== structural vs === referential)
Start
Compare with == ?
Check structural
Return true
True
Return true
No
Return false
First, Kotlin checks structural equality with ==, then referential equality with === if needed, returning true or false accordingly.
Execution Sample
Kotlin
val a = "hello"
val b = String("hello".toCharArray())
println(a == b)
println(a === b)
Compares two strings a and b using structural (==) and referential (===) equality.
Execution Table
StepExpressionEvaluationResult
1a == bCompare contents of a and btrue
2a === bCompare references of a and bfalse
💡 Both comparisons done; structural equality true, referential equality false.
Variable Tracker
VariableStartAfter 1After 2Final
a"hello""hello""hello""hello"
bnew String("hello".toCharArray())new String("hello".toCharArray())new String("hello".toCharArray())new String("hello".toCharArray())
Key Moments - 2 Insights
Why does 'a == b' return true but 'a === b' return false?
Because '==' checks if the text inside the strings is the same (structural equality), which it is, but '===' checks if both variables point to the exact same object in memory (referential equality), which they do not. See execution_table rows 1 and 2.
Can two different objects be structurally equal?
Yes, two separate objects can have the same content, so '==' returns true even if '===' returns false. This is shown by variables a and b in variable_tracker.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the result of 'a == b' at step 1?
Anull
Btrue
Cfalse
Derror
💡 Hint
Check the 'Result' column in execution_table row 1.
At which step does the referential equality check happen?
AStep 2
BStep 1
CBefore Step 1
DAfter Step 2
💡 Hint
Refer to the 'Expression' column in execution_table to find 'a === b'.
If 'b' was assigned as 'val b = a', what would 'a === b' return?
Afalse
Bnull
Ctrue
Derror
💡 Hint
Refer to variable_tracker and understand that assigning 'b = a' makes both variables point to the same object.
Concept Snapshot
In Kotlin:
- '==' checks structural equality (content).
- '===' checks referential equality (same object).
- Use '==' to compare values.
- Use '===' to check if two variables point to the same object.
- Structural equality can be true even if referential equality is false.
Full Transcript
This example shows how Kotlin compares two strings using '==' and '===' operators. The '==' operator checks if the contents of the strings are the same, which returns true. The '===' operator checks if both variables point to the exact same object in memory, which returns false because they are two different objects with the same content. This helps understand the difference between structural and referential equality in Kotlin.