Kotlin relation of relational equality on Int with values ​​from -128 to 127

I give myself until 12:00 to study and get productivity (I hope) for kotlin.

Following https://kotlinlang.org/docs/kotlin-docs.pdf I tried these snippets on page 17. Can someone help me understand why === returns true if the value is between -128 and 127 ?

The following does print 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 from -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 that if the Int value is outside of -128 to 127 (Java bytes), kotlin creates a new object when assigned, making the link not equal.

+3
kotlin
source share
1 answer

See Java source code Integer.valueOf() , which is not acceptable for values ​​in a box. The javadoc says:

This method will always cache values ​​between -128 and 127

Thus, integers in a block in this range are always the same object if they have the same numerical value.

In Kotlin, you should compare plugin chains with == rather than === .

+7
source share

All Articles