3

Following scenario throws nullptr exception inside if condition block !sample?.SomeField__c:

MyObject__c sample = null;
if (!sample?.SomeField__c) {
   ...
}

Why is that? Shouldn't that be evaluated to !(sample == null ? null : sample.SomeField__c) ?

5
  • 1
    If you try to compile if (!null) { you get "! operator can only be applied to boolean expressions" as that is not a valid expression in Apex. Perhaps the thinking is better to output an NPE error in this case. Something like if (sample?.SomeField__c === false) { might be the way to go. Or probably better to add an extra line of code to establish the boolean value before the if.
    – Keith C
    Aug 24, 2021 at 10:07
  • @KeithC Thank you for clarification, do you know if there is a shorthand for checking if value is null or false?
    – Rechu
    Aug 24, 2021 at 10:22
  • sample?.SomeField__c !== true maybe.
    – Keith C
    Aug 24, 2021 at 10:28
  • Error: Comparison arguments must be compatible types: NULL, Boolean. I think that using simple inequality operator will be enough :)
    – Rechu
    Aug 24, 2021 at 10:33
  • Maybe. Or (Boolean) sample?.SomeField__c !== true.
    – Keith C
    Aug 24, 2021 at 11:39

1 Answer 1

5

Yes, it is compiled to essentially if(sample == null? null: sample.SomeField__c). However, if(null) isn't valid. Just compare to true or false depending on your need.

if(sample?.SomeField__c == true) {

Or:

if(sample?.SomeField__c != false) {

etc.

Even considering that you have to do a comparison, the net construct is still shorter than the original version:

// Shorter
if(sample?.SomeField__c == true) {
// Longer.
if(sample != null && sample.SomeField__c) {

You must log in to answer this question.

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