null.==(obj)不会在scala中抛出空指针异常

前端之家收集整理的这篇文章主要介绍了null.==(obj)不会在scala中抛出空指针异常前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我是斯卡拉的新手.请帮我理解下面的代码片段

null.==("goutam") // ---> return false
null.equals("goutam") // ---> throw NullPointerException

根据我的理解,null是Null特征的唯一实例,它扩展了Anyref和==,并且两者都是AnyRef的函数.那么为什么第一个声明不会抛出而第二个声明呢?

解决方法

Why first statement does not throw but second one does

根据语言规范(6.3),null上有特定的方法,如果调用它们不会导致NullReferenceException发生.它们被定义为:

6.3 The Null Value

The null value is of type scala.Null,and is thus
compatible with every reference type. It denotes a reference value
which refers to a special “null” object. This object implements
methods in class scala.AnyRef as follows:

  • eq(x) and ==(x) return true iff the argument x is also the “null”
    object.
  • ne(x) and !=(x) return true iff the argument x is not also the
    “null” object.
  • isInstanceOf[T] always returns false.
  • asInstanceOf[T] returns the default value of type T.
  • ## returns 0.

A reference to any other member of the “null” object causes a NullPointerException to be thrown.

equals在AnyRef上定义,并且不按照定义处理空值.可以使用eq来检查引用相等性(通常不是你想要做的):

scala> null.==("goutam")
res0: Boolean = false

scala> null.eq("goutam")
res1: Boolean = false

==确实正确处理null,这就是你应该使用的.更多关于Whats the difference between == and .equals in Scala?内容

猜你在找的Scala相关文章