Scala中a.ne(null)和!= null之间有什么区别?

Iva*_*van 15 null scala

我一直在使用

a != null
Run Code Online (Sandbox Code Playgroud)

检查这a不是一个空引用.但现在我遇到了另一种方式:

a.ne(null)
Run Code Online (Sandbox Code Playgroud)

什么方式更好,它们有什么不同?

dre*_*xin 14

就像@Jack所说x ne null的那样等于!(x eq null).之间的差x != nullx ne null!=检查值平等和ne供参考的相等性检查.

例:

scala> case class Foo(x: Int)
defined class Foo

scala> Foo(2) != Foo(2)
res0: Boolean = false

scala> Foo(2) ne Foo(2)
res1: Boolean = true
Run Code Online (Sandbox Code Playgroud)

  • 它们是有区别的。`!=` 可以被覆盖,`ne` 不能。此外,`ne` 只检查引用,而`!=` 可能会检查其他内容。 (2认同)
  • 如果您检查“ null”,我建议您始终使用“ ne”,因为“ null”始终是相同的引用,而您只想检查一下。 (2认同)

om-*_*nom 6

除了说@drexin和@Jack,neAnyRef中定义并且只存在参考类型.

scala> "null".ne(null)
res1: Boolean = true

scala> 1.ne(null)
<console>:5: error: type mismatch;
 found   : Int
 required: ?{val ne: ?}
Note that implicit conversions are not applicable because they are ambiguous:
 both method int2Integer in object Predef of type (Int)java.lang.Integer
 and method intWrapper in object Predef of type (Int)scala.runtime.RichInt
 are possible conversion functions from Int to ?{val ne: ?}
       1.ne(null)

scala> 1 != null
res2: Boolean = true
Run Code Online (Sandbox Code Playgroud)