A concise guide to Apex’s new null coalescing operator (??) introduced in the Spring ’24 release — what it does, when to use it, examples and caveats for Salesforce developers.
Introduction
The Spring ’24 release of Salesforce introduced the null coalescing operator to Apex: the double question mark (??). This operator makes common null-handling patterns more concise by returning the left operand if it is not null, otherwise returning the right operand.
How it works
The syntax is simple:
operand1 ?? operand2
When evaluated, if operand1 is non-null it becomes the result; otherwise operand2 becomes the result. Note: if both operands are null the overall expression can still be null.
Common use cases
The most common scenarios are falling back to default values and removing verbose null checks. For example, replacing a multi-line null check with a single expression:
public List<Contact> getContactsForAccount(Account account) { List<Contact> contacts = contactsForAccount.get(account.Id); if (null == contacts) { contacts = new List<Contact>(); } return contacts; } // Becomes public List<Contact> getContactsForAccountNew(Account account) { List<Contact> contacts = contactsForAccount.get(account.Id) ?? new List<Contact>(); return contacts; }
Chaining
You can chain multiple coalescing operators to pick the first non-null value:
Opportunity opp = opp1 ?? opp2 ?? opp3 ?? opp4 ?? opp5;
Key considerations
- Test coverage: A single-line expression can make one unit test exercise both branches for line-coverage, but you should still test both outcomes explicitly to ensure correct behavior in production.
- Short-circuiting: The right-hand operand is not evaluated if the left-hand operand is non-null — this is efficient and prevents unintended side effects.
- Type compatibility: Both operands must be the same type or promotable to a common type. Casting to a common type (for example
(sObject)
) is possible but can reduce readability. - Readability: Avoid cramming complex operations or queries into operands — prefer clear, maintainable code.
Example: inheritance compatibility
public virtual class First { public String name { get; set; } } public class Second extends First { } First first = new First(); Second second = new Second(); String name = (first ?? second).name;
Further reading
See the official release notes and other language examples:
Conclusion
The null coalescing operator is a welcome addition to Apex that reduces boilerplate and clarifies intent when used judiciously. For Salesforce admins, developers, and architects it’s another tool to write concise, readable code — but remember to keep tests and clarity top of mind when using it in production.
Why this matters: concise null handling reduces bugs and improves maintainability across triggers, controllers, and Apex services where defaults or fallbacks are common.
Leave a Reply