4

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. Commented 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? Commented Aug 24, 2021 at 10:22
  • sample?.SomeField__c !== true maybe. Commented 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 :) Commented Aug 24, 2021 at 10:33
  • Maybe. Or (Boolean) sample?.SomeField__c !== true. Commented 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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.