data class Person(val name: String) fun main() { val p1 = Person("Alice") val p2 = Person("Alice") println(p1 == p2) println(p1 === p2) }
In Kotlin, '==' calls the equals() method, which for data classes compares properties (structural equality). '===' checks if both references point to the same object (referential equality). Since p1 and p2 have the same data but are different objects, p1 == p2 is true and p1 === p2 is false.
class Box(var value: Int) fun main() { val b1 = Box(10) val b2 = Box(10) println(b1 == b2) println(b1 === b2) }
Since Box is a regular class without overriding equals(), b1 == b2 compares references, which are different objects, so it returns false. Also, b1 === b2 is false because they are different objects.
class Point(val x: Int, val y: Int) fun main() { val p1 = Point(1, 2) val p2 = Point(1, 2) println(p1 == p2) }
Regular classes in Kotlin do not override equals() by default. So p1 == p2 compares references, which are different objects, resulting in false. To compare data, use a data class or override equals().
In Kotlin, == calls the equals() method to check if two objects have the same content (structural equality). The === operator checks if two references point to the exact same object (referential equality).
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) }
u1 == u2 is false because u1 is a User object and u2 is null. u1 === u2 is false because they are not the same reference. u2 == null is true because u2 is null. u2 === null is also true because both references are null.