编辑: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
附注对于 Int
和 Long
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/