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 asInt?
or use generics. In these cases numbers boxed in Java classesInteger
,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?