18

我一直在使用

a != null

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

a.ne(null)

哪种方式更好,它们有何不同?

4

2 回答 2

15

就像@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
于 2012-04-08T22:09:44.180 回答
6

除此之外,在 AnyRef 中ne定义的@drexin和 @Jack 仅用于引用类型。

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
于 2012-04-08T22:10:59.040 回答