Scala中`null == last`和`null eq last`之间有什么区别?
我在
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节(空值)有这样的说法:
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |