scala - null.==(obj) 不会在 Scala 中抛出空指针异常

标签 scala scala-collections

我是 Scala 的新手。请帮助我理解下面的代码片段

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

根据我的理解,null 是 Null tr​​ait 的唯一实例,它扩展了 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 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.


equalsAnyRef 上定义并且不处理 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/

相关文章:

scala - 多个 if else 语句从 Scala 中的映射获取非空值

regex - Scala:在正则表达式模式字符串中连接字符串导致问题

xml - 来自 Maven 的 Scalatest : How to tag and filter out an entire Suite?

list - Scala:为什么 foldLeft 不能用于两个列表的连接?

scala - 生成器/ block 到迭代器/流的转换

scala - 使用谓词从 Scala 可变映射中删除元素的正确方法是什么

scala - 为什么 Array 需要 ClassManifest 而不是 List?

scala - Slick 3.0 如何更新变量列列表,只有在运行时才知道哪个数字

scala - 当参数 `list.indexWhere` 为负数时出现 `from` 的奇怪结果

scala - List.view 和 LazyList 有什么区别?