Safe Navigation Operator (?.) first evaluates the Left-Hand-Side of the chain expression. If it is NULL, the Right-Hand-Side is evaluated and returns NULL. We can use this operator in variable, method, and property chaining.
To use the Safe Navigation Operator, we just need to replace the dot (.) with “?.“.
For Example, Account?.Type.
Example: 1
// Creating a NULL reference.
Account objAcc;
// it throws Null Pointer Exception.
System.debug(objAcc.Type);
// it prints the NULL because we used the safe operator
System.debug(objAcc?.Type);
Example: 2
Without Safe Navigation Operator:
String str = 'Salesforce Code Crack';
if(!String.isEmpty(str)){
System.debug(str.capitalize());
}
With Safe Navigation Operator:
String str = 'Salesforce Code Crack';
System.debug(str?.capitalize());
Example: 3
Without Safe Navigation Operator:
list<Account> lstAccs = [SELECT Type FROM Account WHERE Id='0013z00002TAEwaAAH'];
if(lstAccs != null && !lstAccs.isEmpty()){
System.debug(lstAccs[0].Type);
}
With Safe Navigation Operator:
System.debug([SELECT Type FROM Account WHERE Id='0013z00002TAEwaAAH' LIMIT 1]?.Type);
No comments:
Post a Comment