Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

kotlin int boxed identity

In the documentation we have

Note that boxing of numbers does not preserve identity

but the next examples give different results

val number1 = 127
val b1 : Int? = number1
val b2 : Int? = number1
print(b1 === b2) // this prints true

val number2 = 128
val c1 : Int? = number2
val c2 : Int? = number2
print(c1 === c2) // this prints false

In numbers greater than 127 works as expected but not when is above 128 (8 bits), why?

like image 738
Tikiram Ruiz Avatar asked Dec 04 '16 23:12

Tikiram Ruiz


1 Answers

This article explains it: http://javapapers.com/java/java-integer-cache/

The basic idea is that the Java standard lib uses a cache for values between -128 and 127, therefore they always refer to the same Integer object (by identity).

like image 169
David Frank Avatar answered Nov 07 '22 16:11

David Frank