有趣的运营商'==='在Kotlin

Nic*_*heo 20 syntax kotlin

什么操作员'==='在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 = 1000val 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类型.在第二个示例中比较的两个变量是基本类型值,而不是对象.因此,对于它们,引用相等与正则相等完全相同.

  • 我也不是100%肯定,但是AFAIK,`Int`变量(不是`Int?`)被Kotlin编译成原始Java`int`,所以第二次比较中没有涉及任何对象.但我可能错了. (5认同)
  • @JBNizet你是对的,因为那是文档所说的 (3认同)
  • 这并不能真正解释OP的行为.为什么a和b相等,但没有boxedA和anotherBoxedA? (2认同)
  • 编辑答案以更正信息.Kotlin本身不进行任何Int缓存,在这种情况下没有什么可以缓存的. (2认同)