The Kotlin Docs contains the following information.
All nullable references to a are actually the same object because of the memory optimization that JVM applies to Integers between -128 and 127. It doesn’t apply to the b references, so they are different objects.
I wrote the main function and test code to check the above.
At this time, each result was different.
I test this using kotest.
class Ch7Test: StringSpec({
"nullable Int between -128 and 127 should be caching" {
val boxedA: Int? = 100
val anotherBoxedA: Int? = 100
assertSoftly {
(boxedA === anotherBoxedA) shouldBe true
}
}
})
The test result was failed.
expected:<true> but was:<false>
Expected :true
Actual :false
But when I test in main function, the result was different from the test results.
fun main() {
val boxedA: Int? = 100
val anotherBoxedA: Int? = 100
println("debug: ${boxedA === anotherBoxedA}") // output was "debug: true"
}
Why is it the same logic, but the results are different?