4

I am new to scala. Please help me to understand below code snippet

null.==("goutam") // ---> return false
null.equals("goutam") // ---> throw NullPointerException

As per my understanding null is the only instance of Null trait which extends Anyref and == and equals both are functions of AnyRef. so why first statement does not throw but second one does?

Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321
Goutam Chowdhury
  • 271
  • 1
  • 3
  • 12
  • 1
    It makes sense that `null.==("goutam")` doesn't throw `NullPointerException`, because this is the same as `null == "goutam"` (just different method call syntax) and you would not expect that to throw an NPE. – Jesper Oct 31 '16 at 08:48

1 Answers1

7

Why first statement does not throw but second one does

Per the language specification (6.3), there are specific methods on null which will not cause a NullReferenceException to occur if invoked. They're defined as:

6.3 The Null Value

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:

  • eq(x) and ==(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 default value of type T.
  • ## returns 0.

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

equals is defined on AnyRef and doesn't handle null values as per definition. eq, which checks for reference equality (that's usually not what you want to do) can be used:

scala> null.==("goutam")
res0: Boolean = false

scala> null.eq("goutam")
res1: Boolean = false

== does handle null properly, and that is what you should be using. More on that in Whats the difference between == and .equals in Scala?

Community
  • 1
  • 1
Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321