我一直都在使用
a != null
为了检查a
不是空引用,但现在我遇到了另一种方法:
a.ne(null)
哪种方式更好,它们有何不同之处?
正如 @Jack 所说的那样,x ne null
等同于 !(x eq null)
。而 x != null
和 x 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
null
进行比较时,没有区别,对吧? - Jean-Philippe Pellet!=
可以被重载,而 ne
不能。此外,ne
只检查引用,而 !=
可能会检查其他东西。 - drexinnull
,我建议您始终使用ne
,因为null
始终是相同的引用,您只需要检查它即可。 - drexinne
在AnyRef中定义,并且仅适用于引用类型。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
null.eq(null)
是完全有效的,并且返回true
(ne
代表!(this eq that)
)。 - Jack