'Is it safe to use "==" for comparison with null?

I had used expression obj != null for countless times. Sometimes I use null == obj.

I had read piece of scala standard library sources recently and discovered that obj eq null is the only form for comparison used there.

Is it safe to use operator ( that is sugar to .equals) version for null comparison? May some implicit magic crush normal comparison logic with == version?



Solution 1:[1]

You can always use == for object comparison, and nulls will safely use eq over equals when necessary.

See the scaladoc for ==:

Test two objects for equality. The expressionx == that is equivalent to if (x eq null) that eq null else x.equals(that).

So if you have val s: String = null, and you check that s == null, then s eq null is true, so the if is true, and it returns null eq null, which is also true.

In fact, using == is always safer than using equals, because you might actually call s.equals(s) (where s is null), which would throw a NPE.

Solution 2:[2]

Yes it is, I add: If you to speed up your program, use

null == ptr

The program will compile faster

Solution 3:[3]

Yes it is.

In scala, == is to be preferred over equals as it handles null and is aware of numerical equivalence (1==1L but !1.equals(1L))

If you want reference equality, use eq.

Solution 4:[4]

The issue I have whith using == to test against null is illustrated by the code below:

class X {
  override def equals(obj: Any): Boolean = true
}
var x: X = null
println(new X == x) // true and treacherous /!\ 
println(new X == null) // false
println(new X equals x) // true
println(new X equals null) // true
println(new X eq x) // false and sound /!\ 
println(new X eq null) // false

So if you text explicitely against null as in new X == null you're good but if you test against an object stored in a varible and being potentially null, then beware of == if equals was overriden. That's not en issue with eq, so I default to eq. I only use == when I want to use equals, for instance with Strings, never with null.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 TastyCat
Solution 3
Solution 4 Profiterole