0
0
Kotlinprogramming~20 mins

Equality (== structural vs === referential) in Kotlin - Practice Questions

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Kotlin Equality Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of structural vs referential equality
What is the output of this Kotlin code snippet?
Kotlin
data class Person(val name: String)

fun main() {
    val p1 = Person("Alice")
    val p2 = Person("Alice")
    println(p1 == p2)
    println(p1 === p2)
}
A
false
false
B
false
true
C
true
true
D
true
false
Attempts:
2 left
💡 Hint
Remember that '==' checks structural equality and '===' checks if both variables point to the same object.
Predict Output
intermediate
2:00remaining
Equality with mutable objects
What will this Kotlin code print?
Kotlin
class Box(var value: Int)

fun main() {
    val b1 = Box(10)
    val b2 = Box(10)
    println(b1 == b2)
    println(b1 === b2)
}
A
true
true
B
true
false
C
false
false
D
false
true
Attempts:
2 left
💡 Hint
Default '==' for classes without overriding equals compares references.
🔧 Debug
advanced
2:00remaining
Why does this equality check fail?
Consider this Kotlin code. Why does the equality check print false even though the objects have the same data?
Kotlin
class Point(val x: Int, val y: Int)

fun main() {
    val p1 = Point(1, 2)
    val p2 = Point(1, 2)
    println(p1 == p2)
}
ABecause Point class does not override equals(), so '==' compares references which are different.
BBecause '==' always compares references in Kotlin, regardless of class.
CBecause the data in p1 and p2 are different types.
DBecause the println statement is missing parentheses.
Attempts:
2 left
💡 Hint
Check if the class overrides equals() or is a data class.
🧠 Conceptual
advanced
1:30remaining
Difference between == and === in Kotlin
Which statement correctly describes the difference between '==' and '===' in Kotlin?
A'==' checks structural equality by calling equals(), '===' checks referential equality (same object).
B'==' checks referential equality, '===' checks structural equality.
C'==' and '===' both check structural equality but in different ways.
D'==' and '===' are interchangeable and mean the same.
Attempts:
2 left
💡 Hint
Think about how Kotlin compares objects by content vs by reference.
Predict Output
expert
2:30remaining
Output with nullable types and equality
What is the output of this Kotlin code?
Kotlin
data class User(val id: Int)

fun main() {
    val u1: User? = User(5)
    val u2: User? = null
    println(u1 == u2)
    println(u1 === u2)
    println(u2 == null)
    println(u2 === null)
}
A
false
false
false
false
B
false
false
true
true
C
true
false
true
false
D
true
true
true
true
Attempts:
2 left
💡 Hint
Remember how Kotlin handles nulls with '==' and '==='.