kotlin - Kotlin中的引用平等

标签 kotlin

在教程示例中,我正在学习Kotlin:

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
}
为什么两个比较的结果不同?

最佳答案

最可能是因为Integer.valueOf的JDK实现
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.


如果您在Intellij中反编译该方法,则会发现
   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);
   }

关于kotlin - Kotlin中的引用平等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63613583/

相关文章:

android - Dagger2 @Binds 方法的参数类型必须可分配给具有接口(interface)和实现的返回类型

kotlin - Ktor-静态内容路由

android - 实现共享位置地点选择器,与没有地点选择器的 WhatsApp 相同,因为它已被弃用

unit-testing - 测试 Worker 实现 (android workmanager)

java - Android Room 和继承。错误: Multiple fields have the same columnName

Kotlin - 向 ActionBar 添加操作按钮

generics - 方法接收共享相同继承类的类引用

date - Kotlin 只获取明天的日期

java - java 10 和 kotlin 中的 “var”

android - RemoteServiceException 在 MIUI 11 上使我的应用程序崩溃