Scala 中“null == last”和“null eq last”有什么区别?

2023-12-24

我在内置类中看到MessageQueue.scalascala 2.7.7 的第 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, 这是对的吗?有什么区别吗?


当任一侧== is null or如果第一个操作数== 评估为null,那么Scala将不会调用equals。所以,在这种情况下,是的,x == null是相同的x eq null; the equals方法是not调用。请注意以下情况。

考虑一下:

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 than x == null(以防必须调用 equals),但尚未检查。

快乐编码。


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

null 值的类型为 scala.Null,因此与每个引用兼容 类型。它表示一个引用值,引用一个特殊的“空”对象。这个物体 实现类 scala.AnyRef 中的方法如下:

  • [null] eq( x ) 和 [null] ==( x ) 返回 true 当且仅当参数 x 也是“null”对象。
  • ne( x ) 和 !=( x ) 当且仅当参数 x 不是“null”对象时返回 true。
  • isInstanceOf[T ] 始终返回 false。
  • 如果 T 符合, asInstanceOf[T ] 返回“null”对象本身 scala.AnyRef,否则抛出 NullPointerException。

对“null”对象的任何其他成员的引用都会导致 要抛出 NullPointerException。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Scala 中“null == last”和“null eq last”有什么区别? 的相关文章

随机推荐