Interesting operator '===' in Kotlin

2019-02-11 15:53发布

问题:

What operator '===' do in Kotlin? How does it work? Can we check reference equality?

val a: Int = 10000
print(a === a) // Prints 'true'
val boxedA: Int? = a
val anotherBoxedA: Int? = a
print(boxedA === anotherBoxedA) // !!!Prints 'false'!!!

but in case:

var a : Int = 1000
var b : Int = 1000
println(a === b) // print 'true' !!!

val a: Int = 1000 and val b: Int = 1000 is not in range -128..127, but still === is true or compiler in some cases understand that it can be taken one value?

回答1:

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.



标签: syntax kotlin