function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
ram4SFDCram4SFDC 

ternary operator issue in salesforce

What is the difference between the two statments?

 

Decimal total = 0;
Decimal amt;

 

total = total+amt==null?0:amt; // why does this statement throw "argument 1 cannot be null" exception
System.debug(total);

 

total = total+(amt = amt==null?0:amt);// why does this statement work
System.debug(total);

 

 

ForceMantis (Amit Jain)ForceMantis (Amit Jain)

In salesforce all uninitalized variables are set with null. you can not apply addition + operator on null values. In your example you have not initalized amt which is null.

 

In the statement that is working you checking if it is null and if you assigning 0 to it so it works.

sfdcfoxsfdcfox
Decimal total = 0;
Decimal amt;
 
total = total+amt==null?0:amt; // why does this statement throw "argument 1 cannot be null" exception
System.debug(total);
 
total = total+(amt = amt==null?0:amt);// why does this statement work
System.debug(total);

In the first example, it is interpreted as:

 

total = (total+amt==null)?0:amt;

This fails, because amt is null, and you can't add a null value to another value.

 

The second one works because amt is first compared to null, and returns 0 if so before attempting to add to total. You could also make this code shorter:

 

total += amt==null?0:amt;