=== 运算符在 Kotlin 中有什么作用? [英] What does the === operator do in Kotlin?
问题描述
运算符 ===
在 Kotlin 中有什么作用?它是如何工作的?我们可以检查引用相等性吗?
What does 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'!!!
但以防万一:
var a : Int = 1000
var b : Int = 1000
println(a === b) // print 'true' !!!
val a: Int = 1000
和 val b: Int = 1000
不在 -128..127
范围内,但仍然 ====
是真的还是编译器在某些情况下理解它可以取一个值?
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?
推荐答案
作为 documented,它代表 参照平等:
引用相等性由 === 操作(及其否定的对应项 !==)检查.当且仅当 a 和 b 指向同一个对象时,a === b 的计算结果为真.
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
}
将此与下面的 Java 代码进行比较:
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
}
你的例子:
此外,正如此处所述,数字装箱并不能保留身份".因此,boxedA
将有一个身份,但 anotherBoxedA
将有另一个身份.两者都有结构相等,但不是指称相等.
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.
但是为什么第二个有效?因为 Kotlin Int
类型对应于 Java int
类型.第二个例子中比较的两个变量是原始类型值,而不是对象.因此,对它们来说,引用相等与常规相等完全相同.
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.
这篇关于=== 运算符在 Kotlin 中有什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!