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?
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 expression
x == thatis equivalent toif (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.
Yes it is, I add: If you to speed up your program, use
null == ptr
The program will compile faster
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With