我是斯卡拉的新手.请帮我理解下面的代码片段
null.==("goutam") // ---> return false null.equals("goutam") // ---> throw NullPointerException
根据我的理解,null是Null特征的唯一实例,它扩展了Anyref和==,并且两者都是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上定义,并且不按照定义处理空值.可以使用eq来检查引用相等性(通常不是你想要做的):
scala> null.==("goutam") res0: Boolean = false scala> null.eq("goutam") res1: Boolean = false
==确实正确处理null,这就是你应该使用的.更多关于Whats the difference between == and .equals in Scala?的内容