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?