``` val number:Int = 127 val boxedNumber: I...
# getting-started
g
Copy code
val number:Int = 127
    val boxedNumber: Int? = number
    val anotherBoxedNumber: Int? = number
    println(boxedNumber === anotherBoxedNumber) // true
Why does this case exist? And why it only works for byte ranged numbers?
j
On the JVM, boxed instances of
Integer
are cached for low int values
r
g
@Joffrey it's true for Long too:
Copy code
val number:Long = 127
val boxedNumber: Long? = number
val anotherBoxedNumber: Long? = number
println(boxedNumber === anotherBoxedNumber) // true
👌 1
@Riccardo Lippolis thanks for the link! reading right now
r
there are cached values for boxed versions of multiple primitive data types, so e.g.
Integer
,
Long
,
Short
,
Byte
,
Character
,
Boolean
j
The specification defines this cache in section "5.1.7. Boxing Conversion" here: https://docs.oracle.com/javase/specs/jls/se22/html/jls-5.html#jls-5.1.7 So it talks about "integer values" in general, but this should cover byte/short/int/long. Note that this caching is defined as a minimum, but different implementations of the JVM may choose to cache more
🙌 1
r
ah yeah, Short, forgot that one 😅
j
Overall, you shouldn't make assumptions about the identity of these types, boxed or not. This is why Kotlin forbids
===
for primitives, by the way. Use
==
instead to check for equality (not identity)
💡 1
🙌 1
g
Thanks a lot! @Joffrey @Riccardo Lippolis. I got it now)