我一直在使用
a != null
Run Code Online (Sandbox Code Playgroud)
检查这a不是一个空引用.但现在我遇到了另一种方式:
a.ne(null)
Run Code Online (Sandbox Code Playgroud)
什么方式更好,它们有什么不同?
dre*_*xin 14
就像@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
Run Code Online (Sandbox Code Playgroud)
除了说@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
Run Code Online (Sandbox Code Playgroud)