In this blog, we will be going to discuss the Null Coalescing Operator in Salesforce that we just got in the Salesforce latest Spring’24 release. Earlier we used to put lots of logic to avoid null pointer exceptions in our code. It is an elegant way of replacing those if/else blocks.
The null coalescing operator is a binary operator in the form a ?? b that returns a if a isnβt null and otherwise returns b.
How to use this operator?
Let’s understand with an example
Firstly, we will check how traditional if/else work
Now let’s check with the ternary operator
Null Coalescing operator
It is the left-associative operator. Furthermore, similar to the safe navigation operator (?.), this operator (??) replaces verbose and explicit checks for null references in code.
It first checks the left-hand operand and if that is null then operates the right-hand operand. Like, the above if intValue is null then only outputValue will become 100 otherwise outputValue will be 1.
Let’s check how it will work on multiple If/else conditions.
Here, we are checking if s1 is not null; then, assigning the value of s1 to outputVal and doing the same with other variables. As we can see, it took multiple lines of code just to execute an assignment and to avoid null conditions. Now, with our new operator (??), we can bypass those multiple lines of code, which enhances our performance and also improves code readability.
How can we implement the above scenario with fewer lines of code?
Syntax
OUTPUT
Now, if all the conditions are null, it will assign the default value that we have provided. This is because it executes when all conditions yield null.
If we don’t provide the default value here and all the values are null it will assign the null value to the variable.
While working with this new operator we need to consider one thing which is type compatibility between operands.
Let us understand it with an example. Let’s modify a few lines in the above code to understand this
Hence, if we try to execute it, we will get this error “Incompatible types in null coalescing operator”. So, we must ensure the compatibility between operands.
FAQ’s
1. What is a safe navigation operator?
It displays as ?.Β For example: a?.b which means if a is not null then a.b gets evaluated otherwise it will return null.
For Example: Below is BillingCity of the first account in the acts list is null return null else return BillingCity in uppercase.
Syntax
OUTPUT
2. How does null coalescing work with SOQL?
Syntax
OUTPUT
Also Read – Batch Apex Scenario-Based Interview Questions and Answers
Conclusion
In conclusion, this new operator is a great way of reducing the lines of code just to check null conditions. Moreover, it enhances code readability and performance.
One thought on “Null Coalescing Operator in Salesforce”