Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin referential equality behavior on Int with values between -128 to 127

Tags:

kotlin

I'm giving myself until 12:00AM to learn and get productive (hopefully) on kotlin.

Following https://kotlinlang.org/docs/kotlin-docs.pdf I tried these snippets on page 17. Could anyone please help me understand why === returns true if a value is between -128 to 127?

The following indeed prints false:

val a: Int = 10000
val boxedA: Int? = a            // Integer@445
val anotherBoxedA: Int? = a     // Integer@447 why?
print(boxedA === anotherBoxedA) // false

However changing a to any value between -128 to 127 always prints true:

val a: Int = -128
val boxedA: Int? = a            // Integer@445
val anotherBoxedA: Int? = a     // Integer@445 why?
print(boxedA === anotherBoxedA) // true!

It seems to me if Int value is outside the bounds of -128 to 127 (Java byte) kotlin creates a new object on assignment does making the reference not equal.

like image 297
Quirino Gervacio Avatar asked Dec 17 '25 14:12

Quirino Gervacio


1 Answers

See the Java source code of Integer.valueOf() which is reponsible for boxing int values. The javadoc says:

This method will always cache values in the range -128 to 127

So boxed integers in that range are always the same object if they have the same numeric value.

In Kotlin, you should compare boxed Integers with == and not with ===.

like image 198
Ingo Kegel Avatar answered Dec 19 '25 06:12

Ingo Kegel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!