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

时间:2012-04-08 22:00:58

标签: scala null

我一直在使用

a != null

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

a.ne(null)

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

2 个答案:

答案 0 :(得分:12)

与@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

答案 1 :(得分:5)

除了说@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