1

From documentation on kotlinlang.org

Numbers representation on the JVM
On the JVM platform, numbers are stored as primitive types: int, double, and so on. Exceptions are cases when you create a nullable number reference such as Int? or use generics. In these cases numbers boxed in Java classes Integer, Double, and so on.

Note that nullable references to the same number can be different objects:

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

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

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

    val c: Int = 101
    val boxedC: Int? = c
    val anotherBoxedC: Int? = c

    println(boxedC === anotherBoxedC) // true
}

Unexpected behavior: if variable c takes a value of 101 then the expression (boxedC === anotherBoxedC) returns true. What is the explanation for this behaviour?

  • 1
    in the JVM, Integer caches values between `[-128,127]` (and may cache other values outside of this range) so your `boxedC` and `anotherBoxedC` are the same object, hence the `===` yields true. [Integer in JVM](https://docs.oracle.com/javase/8/docs/api/java/lang/Integer.html) and [Discussion on this on kotlinlang](https://discuss.kotlinlang.org/t/boxing-of-number-giving-true-for-number-less-than-128/15927) – AlexT Mar 10 '21 at 16:29
  • 1
    Although this stuff is good to know about, in practice it shouldn't matter because you should never need to compare boxed primitives by reference.  In Java, it's fairly common because calling `.equals()` is a lot of hassle, especially if you have to take nulls into account — but in Kotlin, `==` is even easier than `===`! – gidds Mar 10 '21 at 21:24

0 Answers0