我一直一直使用
a != null
检查a
是不是空引用。 但现在我已经见过用另一种方式:
a.ne(null)
什么样的方式更好,他们如何不同?
我一直一直使用
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
除此之外说@drexin和@Jack, ne
定义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