17

While reviewing a teammate's code, I was surprised to find the following pattern, which works:

static void myFunction(List<String> stringArray) {
   if (stringArray?.size() > 0) {
      System.debug('do more stuff');
   }
}

I thought this code would throw an exception if someone called the function with myFunction(null), because you shouldn't be able to compare a null with an Integer. But it turns out it behaves nicely. Observe the following Execute Anonymous script:

List<String> myList = null;
System.debug(myList?.size()); // null
System.debug(myList?.size() > 0); // false (no exception here!)

Now, I realize that the following also doesn't throw an exception...

Integer myInt = null;
System.debug(myInt > 0); // false

But this code gives you a compile error:

System.debug(null > 0);

Taking a step back, I'm not exactly sure what distinguishes an Integer that's null from a null that's null, but it seems the Safe Navigation Operator knows how to deal with these distinctions. Is there more developers should know about the SNO and how it can be used in comparisons like this, beyond what the docs describe?

1 Answer 1

26

You've noticed an important change, but it flew under your radar, apparently. The Boolean operators, <, >, <=, and >= are now null-safe. Previously, if either side was null, this resulted in an exception being thrown, but now they simply return false, which is actually consistent with how JavaScript handles null values in Boolean comparisons.

You can't actually compare the literal null via the four operators above to anything, because it's a different data type (this is actually a compilation error, not a runtime error), similar to trying to compare a custom user class to an Account record; they're simply incompatible types for comparison. You can actually cast the null to an Integer, and it suddenly works as the variable version in your question:

System.debug((Integer)null > 0);

So, the SNO isn't the big deal here, it's that Boolean operators are now null-safe, so SNO doesn't need to do anything special other than return a null value when it reaches a dead-end.

This is now in the documentation:

If x or y equal null and are Integers, Doubles, Dates, or Datetimes, the expression is false.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .