いつも使っています
a != null
anull 参照ではないことを確認します。しかし今、私は別の使い方に出会いました:
a.ne(null)
どの方法が優れていて、どのように違うのですか?
@Jackx 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 は AnyRef で定義neされ、参照型に対してのみ存在します。
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