加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-16 18:06:25 所属栏目:安全 来源:网络整理
导读:我是斯卡拉的新手.请帮我理解下面的代码片段 null.==("goutam") // --- return falsenull.equals("goutam") // --- throw NullPointerException 根据我的理解,null是Null特征的唯一实例,它扩展了Anyref和==,并且两者都是AnyRef的函数.那么为什么第一个声明不
我是斯卡拉的新手.请帮我理解下面的代码片段

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?的内容

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读