As documented, it represents Referential Equality:
Referential equality is checked by the === operation (and its negated counterpart !==). a === b evaluates to true if and only if a and b point to the same object.
Referential equality means that two references point to the same object. Per instance:
fun main(args: Array<String>) {
val number1 = Integer(10) // create new instance
val number2 = Integer(10) // create new instance
val number3 = number1
// check if number1 and number2 are Structural equality
println(number1 == number2) // prints true
// check if number1 and number2 points to the same object
// in other words, checks for Referential equality
println(number1 === number2) // prints false
// check if number1 and number3 points to the same object
println(number1 === number3) // prints true
}
Compare this to the Java code below:
public static void main(String[] args) {
Integer number1 = new Integer(10); // create new instance
Integer number2 = new Integer(10); // create new instance
Integer number3 = number1;
// check if number1 and number2 are Structural equality
System.out.println(number1.equals(number2)); // prints true
// check if number1 and number2 points to the same object
// in other words, checks for Referential equality
System.out.println(number1 == number2); // prints false
// check if number1 and number3 points to the same object
System.out.println(number1 == number3); // prints true
}
Your example:
Also, as documented here, "boxing of numbers does not preserve identity". So, boxedA
will have one identity, but anotherBoxedA
will have another one. Both have structural equality, but not referential equality.
But why the second one works? Because the Kotlin Int
type corresponds to the Java int
type. The two variables compared in the second example are primitive type values, not objects. Therefore, for them the reference equality is exactly the same as regular equality.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…