Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

scala

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?

like image 789
ayvango Avatar asked May 15 '26 17:05

ayvango


2 Answers

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.

like image 126
Michael Zajac Avatar answered May 19 '26 02:05

Michael Zajac


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

null == ptr

The program will compile faster

like image 20
TastyCat Avatar answered May 19 '26 03:05

TastyCat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!