Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reference Equality in Kotlin

Tags:

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?

like image 606
quangdien Avatar asked Aug 27 '20 09:08

quangdien


1 Answers

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);
   }
like image 121
Yuri Schimke Avatar answered Nov 15 '22 07:11

Yuri Schimke