Use of Null Coalescing Operator
The new null coalescing operator (??) simplifies code with verbose null checks.
For example -
Old Ways -
Example 1 -Integer notNullReturnValue;
if (anInteger != null){
notNullReturnValue = anInteger;
} else {
notNullReturnValue = 100;
}
Example 2 -
Integer notNullReturnValue = (anInteger != null) ? anInteger : 100;
New Way (Null Coalescing Operator) -
Integer anInteger; // Assume this is passed as parameter and can be NULL
Integer notNullReturnValue = anInteger ?? 100;
Note: nullish coalescing operator (??) is also part of modern JavaScript APIs. You can also use them in your Lightning Web Components (LWCs) to simplify null checks.
When using the null coalescing operator, always remember operator precedence. In some cases, using parentheses is necessary to obtain the desired results.
For example, the expression top ?? 100 - bottom ?? 0 evaluates to top ?? (100 - bottom ?? 0) and not to (top ?? 100) - (bottom ?? 0).
You can assign a single resultant record from a SOQL query in Apex. However, if the query doesn't return any rows, it throws an exception. To handle this gracefully, you can use the null coalescing operator. If you use a SOQL query as the left-hand operand of the operator and it returns rows, then the operator will return the query results. But if no rows are returned, the operator will return the right-hand operand.
Here are a few more examples -
Account defaultAccount = new Account(name = 'Acme');// Left operand SOQL is empty, return defaultAccount from right operand:
Account a = [SELECT Id FROM Account WHERE Id = '001000000FAKEID'] ?? defaultAccount;
// If there isn't a matching Account or the Billing City is null, replace the value
string city = [Select BillingCity From Account Where Id = '001xx000000001oAAA']?.BillingCity;
System.debug('Matches count: ' + (city?.countMatches('San Francisco') ?? 0) );
There are some restrictions on using the null coalescing operator.
You can’t use the null coalescing operator as the left side of an assignment operator in an assignment. foo??bar = 42;// This is not a valid assignment
SOQL bind expressions don’t support the null coalescing operator.
String primaryName;String secondaryName = 'Acme';
String acctName = primaryName ?? secondaryName;
List<Account> accounts = [SELECT Name FROM Account WHERE Name = :acctName];
List<List<SObject>> moreAccounts = [FIND :acctName IN ALL FIELDS
RETURNING Account(Name)];
Resources
Null Checks in LWC Using Null Coalescing Operator

Comments
Post a Comment