I have a problem with nullable variable in Kotlin I found this example in the Kotlin docs:
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
output
true
false
They explain that this is the memory optimization that JVM applies to Integer s between -128 and 127. It doesn't apply to the b references, so they are different objects.
then I convert a and b to nullable
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) // true
output
true
true
What makes this difference? Can anyone please explain to me?