Null == (obj) does not throw a null pointer exception in scala

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

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

According to my understanding, null is the only instance of the Null attribute that extends Anyref and == and is equal, both are AnyRef functions. so why the first operator does not quit, and the second does?

+4
source share
1 answer

Why the first operator does not quit, and the second does

In accordance with the specification of the language (6.3), nullthere are special methods that will not cause an appearance NullReferenceExceptionwhen called. They are defined as:

6.3 Null

null scala.Null , , . "" . scala.AnyRef :

  • eq(x) ==(x) true, x "" .
  • ne(x) !=(x) true, x "null".
  • isInstanceOf[T] false.
  • asInstanceOf[T] T.
  • ## 0.

"" NullPointerException.

equals AnyRef null . eq, ( , ):

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

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

== null, . == .equals Scala?

+7

Source: https://habr.com/ru/post/1659382/


All Articles