- changed title to Safe navigation operator misses possible hard to catch error
Flag usages of the safe navigation operator in contexts that expect/require a non-null value
I had a code snippet where I used the safe navigation operator and I think I’ve found an APEX issue, where IC2 could provide help as well (but IMHO source push should not succeed)
Take this code:
if (null) {
System.debug('whoa');
}
When executing it, apex compiler correctly signals an error: Compile failure on line 1, column 5: Condition expression must be of type Boolean: NULL
The condition is clearly null
which is not allowed
When I have this code:
String s = null;
if (s?.containsIgnoreCase('foo')) {
System.debug('whoa');
}
This is valid code but runtime will cause a null reference exception because if becomes an if (null)
when s
is null, but explicitly doing that is compile time error.
The result of the expression is null | Boolean
and APEX (and other languages) only allows Boolean
.
What do you think Scott?
Comments (6)
-
reporter -
repo owner Interesting suggestion, and it can be generalized to flagging any expression that is expected to resolve to a non-null value but includes the safe navigation operator, e.g.,
myInstance?.myCounter++
. Yeah, I think this is worth flagging in the existing safe navigation operator usage code inspection. Thanks for filing! -
repo owner Yeah, I like this proposal. I implemented it this morning and it definitely adds more “safe” to the safe navigation operator, e.g.:
This should be included in next week’s build as an enhancement to the existing Safe Navigation Operator Usage code inspection.
-
repo owner - changed title to Flag usages of the safe navigation operator in contexts that expect/require a non-null value
- marked as enhancement
-
reporter Awesome, thanks Scott, I hope it can help others as well ;-)
-
repo owner - changed status to resolved
Delivered in 2.2.3.7.
- Log in to comment