20

I have been always using

a != null

to check that a is not a null reference. But now I've met another way used:

a.ne(null)

what way is better and how are they different?

Ivan
  • 63,011
  • 101
  • 250
  • 382
  • 1
    I don't know scala but in general it's not good to invoke a method on the object if you don't know if it's null or not. In many languages this will provoke a 'NullPointerException' . – nuala Apr 08 '12 at 22:03
  • 1
    @yoshi: this is not true in Scala, actually `null.eq(null)` is perfectly valid and returns `true` (`ne` stands for !(this eq that)`) – Jack Apr 08 '12 at 22:05
  • The other way round with a reference to your specific question: http://stackoverflow.com/questions/7055299/whats-the-difference-between-null-last-and-null-eq-last-in-scala – assylias Apr 08 '12 at 22:08

2 Answers2

16

Like @Jack said x ne null is equal to !(x eq null). The difference between x != null and x ne null is that != checks for value equality and ne checks for reference equality.

Example:

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
fredoverflow
  • 256,549
  • 94
  • 388
  • 662
drexin
  • 24,225
  • 4
  • 67
  • 81
  • 1
    So, in practice, when comparing with `null`, there's no difference, right? – Jean-Philippe Pellet Apr 08 '12 at 22:10
  • 2
    There is a difference. `!=` can be overriden, `ne` can't. Also `ne` just checks for the reference, while `!=` might check for other things. – drexin Apr 08 '12 at 23:23
  • 1
    But it is still not clear for me practically: how should I check a String argument to be not null: with != or with ne? – Ivan Apr 11 '12 at 17:55
  • 5
    If you check for `null`, I would suggest you to always use `ne`, because `null` is always the same reference and you only want to check for that. – drexin Apr 11 '12 at 18:53
6

Besides that said @drexin and @Jack, ne defined in AnyRef and exists only for referential types.

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
om-nom-nom
  • 62,329
  • 13
  • 183
  • 228
  • "and exists only for referential types" do you mean there are value types in Scala? – Ivan Apr 08 '12 at 22:16