什么操作员'==='在Kotlin做什么?它是如何工作的?我们可以检查参考平等吗?
val a: Int = 10000
print(a === a) // Prints 'true'
val boxedA: Int? = a
val anotherBoxedA: Int? = a
print(boxedA === anotherBoxedA) // !!!Prints 'false'!!!
Run Code Online (Sandbox Code Playgroud)
但以防万一:
var a : Int = 1000
var b : Int = 1000
println(a === b) // print 'true' !!!
Run Code Online (Sandbox Code Playgroud)
VAL a: Int = 1000和val b: Int = 1000不在范围内-128..127,但仍然===是真实的或编译器在某些情况下明白,它可以采取一个价值?
mar*_*ira 34
如文档所述,它代表了参考平等:
参数相等性由===操作(及其否定的对应物!==)检查.当且仅当a和b指向同一个对象时,a === b的计算结果为true.
引用相等意味着两个引用指向同一个对象.每个实例:
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
}
Run Code Online (Sandbox Code Playgroud)
将其与下面的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
}
Run Code Online (Sandbox Code Playgroud)
此外,如此处所述,"数字装箱不会保留身份".所以,boxedA将有一个身份,但anotherBoxedA将有另一个.两者都有结构平等,但没有参照平等.
但为什么第二个有效?因为Kotlin Int类型对应于Java int类型.在第二个示例中比较的两个变量是基本类型值,而不是对象.因此,对于它们,引用相等与正则相等完全相同.
| 归档时间: |
|
| 查看次数: |
4375 次 |
| 最近记录: |