我是 Scala 的新手。请帮助我理解下面的代码片段
null.==("goutam") // ---> return false
null.equals("goutam") // ---> throw NullPointerException
根据我的理解,null 是 Null trait 的唯一实例,它扩展了 Anyref 和 == 并且 equals 都是 AnyRef 的函数。那么为什么第一个语句不会抛出但第二个语句会抛出?
最佳答案
Why first statement does not throw but second one does
根据语言规范 (6.3),在
null
上有特定的方法。这不会导致 NullReferenceException
调用时发生。它们被定义为:6.3 The Null Value
The
null
value is of typescala.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 classscala.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
在 AnyRef
上定义并且不处理 null
根据定义的值。 eq
,可以使用检查引用相等性(这通常不是您想要做的):scala> null.==("goutam")
res0: Boolean = false
scala> null.eq("goutam")
res1: Boolean = false
==
处理null
正确,这就是你应该使用的。更多详情请见 Whats the difference between == and .equals in Scala?
关于scala - null.==(obj) 不会在 Scala 中抛出空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40338611/