Search code examples
kotlinnullableequalityboxingautoboxing

Why Kotlin '===' reference equality operator returns false for same object references?


The example are from Kotlin official website

    val a: Int = 100
    val boxedA: Int? = a
    val anotherBoxedA: Int? = a     

    val b: Int = 100
    val boxedB: Int? = b
    val anotherBoxedB: Int? = b

    println(a === a)  // true
    println(boxedA === anotherBoxedA) // true
    println(boxedB === anotherBoxedB) // true

I understood above example. But when I change the value of a and b from 100 to 1000, the output changes to false from true like below :

    val a: Int = 1000
    val boxedA: Int? = a
    val anotherBoxedA: Int? = a     
    
    val b: Int = 1000
    val boxedB: Int? = b
    val anotherBoxedB: Int? = b

    println(a === a)  // true
    println(boxedA === anotherBoxedA) // false
    println(boxedB === anotherBoxedB) // false

Can anyone help by changing value from 100 to 1000, why output of === operator is changing?

What is happening with respect to autoboxing?


Solution

  • Auto-boxing uses a cache for the small integers (I guess up to 127), Therefore you get the same object if you box a small integer, but a different one if you box a large integer.