gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 10:29:23 24 4
gpt4 key购买 nike

我在内置类中看到MessageQueue.scala在 Scala 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 , 这是正确的吗?有什么区别吗?

最佳答案

== 的任一侧是 null或者如果 == 的第一个操作数计算结果为 null,那么 Scala 将不会调用 equals .所以,在这种情况下,是的,x == nullx 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.

关于scala - Scala 中的 `null == last` 和 `null eq last` 之间有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7055299/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com