1

I don't understand why boxedA === anotherBoxedA returns true.

And boxedB === anotherBoxedB return false

    val a: Int = 100
    val boxedA: Int? = a
    val anotherBoxedA: Int? = a
    val b: Int = 10000
    val boxedB: Int? = b
    val anotherBoxedB: Int? = b
    println(boxedA === anotherBoxedA) // true
    println(boxedB === anotherBoxedB) // false
}
Artaza Sameen
  • 519
  • 1
  • 5
  • 13
  • Why are these named boxed? Kotlin doesn't have primitives. – Abhijit Sarkar Feb 20 '21 at 04:09
  • It's written in the official documentation. the documentation is referring them as boxed – Artaza Sameen Feb 20 '21 at 04:13
  • @AbhijitSarkar It does, at least when targeting the JVM. If you just have `Int` then it uses the primitive `int` under-the-hood. But if you have something like `List` then it uses `List` (i.e. a list of boxed integers) under-the-hood. – Slaw Feb 20 '21 at 04:13
  • @Slaw I suppose you're referring to [this](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-int/) part of the docs _On the JVM, non-nullable values of this type are represented as values of the primitive type int._ What I meant is that the language doesn't have primitives; what it does at bytecode level shouldn't be reflected in the code because it makes no sense to those reading the code. – Abhijit Sarkar Feb 20 '21 at 04:20
  • @AbhijitSarkar You should tell this to Kotlin's documentation authors then: https://kotlinlang.org/docs/basic-types.html#numbers-representation-on-the-jvm – Alexey Romanov Feb 20 '21 at 06:07
  • @AlexeyRomanov Just did. There's a feedback form at the bottom of the page you referred to. – Abhijit Sarkar Feb 20 '21 at 06:09
  • Can somebody explain why's the same question is asked over 5+ times? I swear I saw this alot within last two months. – Animesh Sahu Feb 20 '21 at 13:47
  • @AnimeshSahu Same teacher, perhaps? SO is the biggest homework dump these days. – Abhijit Sarkar Feb 21 '21 at 06:12

1 Answers1

3
fun main() {
    for (i in 1..10000) {
        val a: Int? = i
        val b: Int? = i
        
        val same = a === b
        if (!same) {
            println(i)
            break
        }
    }
}

128

JLS, section 5.1.7; object identity must be given for values -128 to 127 inclusive.

Integer#valueOf(int) also documents this behavior:

this method is likely to yield significantly better space and time performance by caching frequently requested values. This method will always cache values in the range -128 to 127, inclusive, and may cache other values outside of this range.

See this answer for more details.

Abhijit Sarkar
  • 21,927
  • 20
  • 110
  • 219