Blog

Null Coalescing Operator on Apex in Salesforce

Do you know about Null Coalescing Operator on Apex in Salesforce?

The ?? operator returns the left-hand argument if it is not null. Otherwise, it will return the right-hand argument. Like the safe navigation operator (?.), the null coalescing operator (?.), replaces verbose and explicit checks for null references in code.

The null coalescing operator (A ?? B) is a binary operator that yields A if A is not null and B otherwise. The operator is left associative. The left-hand operand is evaluated only once. The right-hand operand is only evaluated when the left-hand operand is null.

Before Null Coalescing Operator :

Integer emptyValue = (variableA != null) ? variableA : 5;

After Null Coalescing Operator :

Integer emptyValue = variableA ?? 5;

Null Coalescing Operator on Queries

Apex allows you to assign a single resultant record from a SOQL query, but it will throw an exception if the query returns no rows. The null coalescing operator can be used to handle scenarios where the query returns no rows properly. If the operator’s left-hand operand is a SOQL query with rows returned, the null coalescing operator provides the query results. If there are no rows returned, the null coalescing operator returns the right-hand operand.

Example on Queries

Case caseRecord = new Case(priority =’High’);

Case cse =[Select Id,Priority from Case where Id=’5001300000FAKEIDS’] ??

caseRecord;

Assert.areEqual(cse, acaseRecord);