Blog

Null Coalescing Operator on Apex in Salesforce

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

The ?? operator, known as the Null Coalescing Operator on Apex in Salesforce, returns the left-hand argument if it is not null. Otherwise, it returns 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);

 

We are Inno Valley Works, We are a passionate team of developers, best thinkers and consultants who can solve anything and everything.
With our highly engaging team, you can easily bring the vision to all your business ventures come true.
We have team, put your problem, get your solution

 

🎥 Check Out Our YouTube Channel

Explore helpful tutorials, product updates, and feature walkthroughs from the team at Innovalley Works.

👉 Visit Our Channel