quangdien
quangdien

Reputation: 349

Reference Equality in Kotlin

I'm learning Kotlin, in the tutorial example:

fun main() {
    val a: Int = 100
    val boxedA: Int? = a
    val anotherBoxedA: Int? = a

    val b: Int = 1000
    val boxedB: Int? = b
    val anotherBoxedB: Int? = b

    println(boxedA === anotherBoxedA) // true
    println(boxedB === anotherBoxedB) // false
}

Why is the result of two comparision different?

Upvotes: 5

Views: 78

Answers (1)

Yuri Schimke
Yuri Schimke

Reputation: 13448

Most likely because of the JDK implementation of Integer.valueOf

https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#valueOf(int)

Returns an Integer instance representing the specified int value. If a new Integer instance is not required, this method should generally be used in preference to the constructor Integer(int), as 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.

If you decompile the method in Intellij, you'll find

   public static final void main() {
      int a = 100;
      Integer boxedA = Integer.valueOf(a);
      Integer anotherBoxedA = Integer.valueOf(a);
      int b = 1000;
      Integer boxedB = Integer.valueOf(b);
      Integer anotherBoxedB = Integer.valueOf(b);
      boolean var6 = boxedA == anotherBoxedA;
      boolean var7 = false;
      System.out.println(var6);
      var6 = boxedB == anotherBoxedB;
      var7 = false;
      System.out.println(var6);
   }

Upvotes: 6

Related Questions