I see in the built-in class MessageQueue.scala
of scala 2.7.7, around line 164, it's:
def extractFirst(p: Any => Boolean): MessageQueueElement = {
changeSize(-1) // assume size decreases by 1
val msg = if (null eq last) null
else {
...
}
}
I don't understand val msg = if (null eq last) null
well, why it uses eq
, but not null
. If I write if (last==null) null
, is it correct? Is there any difference?
The operator
==
in scala is different from Java's.In scala,
==
is equivant toequals
method in Any,eq
is equivant to==
in JavaBTW, why doesn't null.asInstanceOf[Int], null.asInstanceOf[Double], null.asInstanceOf[Boolean], null.asInstanceOf[Char] throw NullPointerException ?
When either side of the
==
isnull
or if the first operand of==
evaluates to null, then Scala will not invokeequals
. So, in this case, yes,x == null
is the same asx eq null
; theequals
method is not invoked. Pay attention to the cases below.Consider this:
And note that:
Results in a warning saying a "a fresh object" will never be equal (to null).
I suspect there may be slightly more/different code emitted for
x == y
thanx == null
(in case the equals must be invoked), but have not checked.Happy coding.
Section 6.3 (The Null Value) of the Scala Language Specification has this to say: