有趣的运算符'==='在Kotlin

什么运算符'==='在Kotlin中做什么? 它是如何工作的? 我们可以检查参考平等吗?

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

但在以下情况下:

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

val a: Int = 1000val b: Int = 1000不在-128..127范围内,但是===仍然是true,或者编译器在某些情况下明白它可以取一个值?

如文件所述 ,它代表了参照平等

引用相等是通过===操作(和它的否定对象!==)检查的。 a === b当且仅当a和b指向同一个对象时才计算为真。

引用相等意味着两个引用指向同一个对象。 每个实例:

 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 } 

将其与以下Java代码进行比较:

 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 } 

你的例子:

另外,正如这里所记载的 ,“数字的装箱并不能保护身份”。 所以, boxedA会有一个身份,但是另一个anotherBoxedA会有另一个身份。 两者都有结构上的平等,但不是指称的平等。

但为什么第二个工作? 因为Kotlin Int类型对应于Java int类型。 在第二个例子中比较的两个变量是基本类型值,而不是对象。 因此,对于他们来说,引用的平等与正则的平等完全相同。