scala - 不一致的空相等检查 scala 2.11.7

标签 scala null boxing unboxing

编辑:Scala 2.12.6 中不再存在此问题

<小时/>

原始问题(针对 Scala 2.11.7):

为什么有这么奇怪的警告?

scala> null.asInstanceOf[Double]
res0: Double = 0.0

scala> null.asInstanceOf[Double] == null
<console>:11: warning: comparing values of types 
      Double and Null using `==' will always yield !!!!false!!!!
       null.asInstanceOf[Double] == null
                                 ^
res1: Boolean = true //!!!!

scala> 0.0 == null
<console>:11: warning: comparing values of types Double and Null using `==' will always yield false
       0.0 == null
           ^
res2: Boolean = false

scala> null.asInstanceOf[Double] == 0.0
res6: Boolean = true

scala> val a = null.asInstanceOf[Double]
a: Double = 0.0

scala> a == null
<console>:12: warning: comparing values of types Double and Null using `==' will always yield false
       a == null
         ^
res7: Boolean = false

附注对于 IntLong

也是如此

P.S.2 这不是重复的 - 这里的问题是,无论 asInstanceOf 如何,装箱根本不会发生(正如您从我的回答中看到的)+警告消息不一致

最佳答案

编辑:这个issue Scala 2.12.6 中不再存在。请参阅pull-request并附有解释。

<小时/>

原始答案(对于 Scala 2.11.7):

null.asInstanceOf[Double] == null 编译为:

aconst_null
ifnonnull

val-版本编译为:

aconst_null
invokestatic unboxToDouble
putfield
aload_0
invokevirtual а
invokestatic boxToDouble
ifnonnull

所以编译器只是忘记在第一种情况下添加 unbox/box

关于scala - 不一致的空相等检查 scala 2.11.7,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35587792/

相关文章:

scala - 如何处理响应超时?

javascript - 是否可以在 Play Framework View 中 console.log ?

postgresql - Postgres 10 横向不嵌套缺少空值

kotlin - 值影响后无法智能转换为 'Boolean'

c# - 扩展 System.Object 时如何避免装箱/拆箱?

scala - jOOQ 将自定义 SQL 获取到映射器中

postgresql - Play 2.5 + Slick application.conf 配置错误与 URL

ios - 检查 getter 中的 CGRect 是否为 null

ios - C# 规范是否允许从 ulong 转换为 int? Monotouch 给出一个 NumberOverflow

java - 使用对象在java中自动装箱拆箱