1

In official Kotlin reference https://kotlinlang.org/docs/reference/basic-types.html#numbers I read that:

Note that boxing of numbers does not necessarily preserve identity

and example which shows how it can be represented:

val a: Int = 10000
print(a === a) // Prints 'true'
val boxedA: Int? = a
val anotherBoxedA: Int? = a
print(boxedA === anotherBoxedA) // !!!Prints 'false'!!!

After some spontaneous testing I realized that it works as should for byte numbers (<128):

val a = 127
val boxedA: Int? = a
val anotherBoxedA: Int? = a
print(boxedA === anotherBoxedA) //!!!Prints 'true'!!!

Also in the same reference https://kotlinlang.org/docs/reference/equality.html I have found that:

For values which are represented as primitive types at runtime (for example, Int), the === equality check is equivalent to the == check

But this doesn't explain this case as for:

val a = 128
val boxedA: Int? = a
val anotherBoxedA: Int? = a
print(boxedA === anotherBoxedA) //!!!Prints 'false'!!!

So I am trying to get a glue why referential equality "===" shows "false" for numbers >=128 and "true" for <128?

Pyts Mike
  • 13
  • 4
  • Due to caching in the JDK. Check out the source code of `Byte.valueOf()`, which is used for boxing. However, when you say it "doesn't work", that isn't true. "It" works every time. – Marko Topolnik Jun 01 '18 at 12:59
  • @MarkoTopolnik thanks will check it and yeah it works always, I rephrased explanation a bit. – Pyts Mike Jun 01 '18 at 13:19
  • https://stackoverflow.com/questions/20897020/why-integer-class-caching-values-in-the-range-128-to-127 – jingx Jun 01 '18 at 14:28

1 Answers1

0

This comes from how Integer.valueOf(int) is implemented for the JVM:

This method will always cache values in the range -128 to 127, inclusive, and may cache other values outside of this range.

So for a = 127 the identity box1 === box2 always holds true, while for all non byte values it might not.

tynn
  • 38,113
  • 8
  • 108
  • 143