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

Scala中`null == last`和`null eq last`之间有什么区别?

发布时间:2020-12-16 19:19:53 所属栏目:安全 来源:网络整理
导读:我在 scala 2.7.7的内置类MessageQueue.scala中看到,在第164行附近,它是: def extractFirst(p: Any = Boolean): MessageQueueElement = {changeSize(-1) // assume size decreases by 1val msg = if (null eq last) nullelse { ... }} 我不明白val msg = if
我在 scala 2.7.7的内置类MessageQueue.scala中看到,在第164行附近,它是:

def extractFirst(p: Any => Boolean): MessageQueueElement = {
changeSize(-1) // assume size decreases by 1

val msg = if (null eq last) null
else {
    ...
  }
}

我不明白val msg = if(null eq last)null,为什么它使用eq,但不是null.如果我写if(last == null)null,它是否正确?有什么区别吗?

解决方法

当==的任一侧为null或者==的第一个操作数计算为null时,Scala将不会调用equals.所以,在这种情况下,是的,x == null与x eq null相同;不调用equals方法.请注意以下情况.

考虑一下:

class X {
   // this is just for testing
   // any equals that returns true when the other object is null
   // is arguably broken. thus even though it may be invoked
   // the end semantics should remain the same
   override def equals(x: Any) = true
}
var x = new X()
x == null // false -- compiler optimization?
null == x // false
var y = null
y == x // false -- see documentation below,y is null,x is not
x == y // true  -- x does not evaluate to null,equals invokes
x eq y // false

请注意:

(new X()) == null

导致警告说“新鲜物体”永远不会相等(为空).

我怀疑可能会为x == y而不是x == null发出稍多/不同的代码(如果必须调用equals),但是没有检查.

快乐的编码.

Scala语言规范的第6.3节(空值)有这样的说法:

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:

  • [null] eq( x ) and [null] ==( 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 “null” object itself if T conforms to
    scala.AnyRef,and throws a NullPointerException otherwise.

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

(编辑:李大同)

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

    推荐文章
      热点阅读