Employ the safe navigation operator (?.) to replace the need for explicit, sequential null reference checks. This innovative operator can swiftly bypass operations on null values and, instead of triggering a NullPointerException, it returns null.
Location: This modification pertains to both Lightning Experience and Salesforce Classic, and it is applicable in Enterprise, Performance, Unlimited, and Developer editions of Salesforce.
Implementation: In situations where the left-hand side of a chained expression results in null, the right-hand side will not be assessed. Integrate the safe navigation operator (?.) when chaining methods, variables, and properties. The unassessed portion of the expression can encompass references to variables, methods, or arrays.
NOTE All Apex types are implicitly nullable and can hold a null value returned from the operator.
EXAMPLE
- This example first evaluates
a
, and returns null ifa
is null. Otherwise, the return value isa.b
.
a?.b // Evaluates to: a == null? Null : a.b
- This example returns null if
a[x]
evaluates to null. Ifa[x]
does not evaluate to null andaMethod()
returns null, then this expression throws a null pointer exception.
a[x]?.aMethod().aField // Evaluates to null if a[x] == null
- This example returns null if
a[x].aMethod()
evaluates to null.
a[x].aMethod()?.aField
- This example indicates that the type of the expression is the same, whether the safe navigation operator is used in the expression or not.
Integer x = anObject?.anIntegerField; // The expression is of type Integer because the field is of type Integer
- This example shows a single statement replacing a block of code that checks for nulls.
// Previous code checking for nulls String profileUrl = null; if (user.getProfileUrl() != null) { profileUrl = user.getProfileUrl().toExternalForm(); }
// New code using the safe navigation operator String profileUrl = user.getProfileUrl()?.toExternalForm();
- This example shows a single-row SOQL query using the safe navigation operator.
// Previous code checking for nulls results = [SELECT Name FROM Account WHERE Id = :accId]; if (results.size() == 0) { // Account was deleted return null; } return results[0].Name;
// New code using the safe navigation operator return [SELECT Name FROM Account WHERE Id = :accId]?.Name;