0

I do not understand this snippet of code I found on the official documentation:

fun main() {
    val a: Int = 100
    val boxedA: Int? = a
    val anotherBoxedA: Int? = a

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

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

Why the equality changes when the variable's value change?

1 Answers1

1

The JVM caches Integers for values between -128 and 127. Integers outside that range may or may not be cached - if they aren't, then each call to Integer i = 128 will return a new object.

Kotlin inherits this behaviour (an Int? in kotlin is an Integer in Java).

So, back to your example:

  • 100 gets cached, hence boxedA and anotherBoxedA are the same object
  • but 100000 is not cached and 2 different instances of Integers are returned
assylias
  • 321,522
  • 82
  • 660
  • 783