我一直在使用
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
除此之外,在 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