Inconsistent null equality check scala 2.11.7

旧时模样 提交于 2019-12-23 16:28:00

问题


Edit: This issue no longer exists in Scala 2.12.6


Original question (for Scala 2.11.7):

Why so strange warning?

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

P.S. Same for Int and Long

P.S.2 It's not a duplicate - the problem here is that boxing doesn't happen at all regardless of asInstanceOf (as you can see from my answer) + the warning message is inconsistent


回答1:


Edit: This issue no longer exists in Scala 2.12.6. See pull-request with explanation.


Original answer (for Scala 2.11.7):

null.asInstanceOf[Double] == null compiles to the:

aconst_null
ifnonnull

The val-version compiles to the:

aconst_null
invokestatic unboxToDouble
putfield
aload_0
invokevirtual а
invokestatic boxToDouble
ifnonnull

So compiler just forgets to add unbox/box in the first case




回答2:


This happens because scala.Double == double in Java, which cannot contain a null value. If you want your desired behaviour you can use java.lang.Double this will be able to store a null value.

val n = null.asInstanceOf[java.lang.Double]
println("null? = " + n)
//null? = null

Another way to prevent the use of double is being more explicit about types

val n: AnyVal = null.asInstanceOf[Double]
println("null? = " + n)
//null? = null

To make things a bit more confusing try this:

println("null? = " + null.asInstanceOf[Double])
//null? = null

This shows the use of double will only happen when your null value is assigned to a val.

I do not have a good explanation for the compiler warning, this warning doesn't seem correct is this specific scenario.



来源:https://stackoverflow.com/questions/35587792/inconsistent-null-equality-check-scala-2-11-7

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!