When we think about conditional statements, the first thing that comes to mind is the traditional if conditional statement. Let’s learn how it has changed during the years when it was first implemented. We will learn about Using a Null Coalescing Operator.
Use cases of Conditional Statements.
We have one Integer value and need to check if the value is not null then return the same number else return 100.
Conditional statements
Integer integerValue = 1;
if(integerValue != null){
return integerValue;
}
else {
return 100;
}
Now, it is a question: Can I cut it short in any way to reduce the lines of code without
disturbing the functionality? Yes, we can do this in another way.
Ternary Operator
Integer integerValue = 1;
System.debug(integerValue != Null ? integerValue : 100);
So far so good, but is there any other way that I can make this shorter without disturbing the
functionality? The answer to this question is Yes. But before going into that, you need to learn about the awesome feature that came with the Sprint 24 release, which is the Null Coalescing operator.
Using Null Coalescing Operator
The ??
operator returns the left-hand argument if the left-hand argument isn’t null. Otherwise, it returns the right-hand argument.
Integer integerValue = 1;
Integer notNullReturnValue = (integerValue != null) ? integerValue : 100;
With the Null-Coalescing Operators, use:
Integer notNullReturnValue = integerValue ?? 100;
Learn more. Learn more about the Salesforce switch case.