How to use Safe Navigation Operator (?.) in Apex | Winter 21 New Feature
Salesforce rolled out a new feature in Winter 21 release, it’s called – SAFE NAVIGATION. Safe navigation operator is a very useful syntax for Salesforce Developers and it will make the coding clean. The main purpose of this syntax is to avoid null pointer exceptions.Basic SyntaxString accountName = accountRecord?.Name;The above statement will store accountRecord.Name value in the variable accountName. As you can understand that accountRecord is basically the sObject variable holding Account record and then we are using that variable to fetch the Name property. Now, what will happen if the accountRecord is null, then null.Name will definitely give the null pointer exception, right? But the answer is No. Because we have used the safe navigation operator(?.) here. Safe navigation operator will make the check and if the accountRecord is not null, then only store the Name field to accountName, otherwise, it will just store null there.How it works:If the left side of the chain expression (?.) evaluates to null, then the right side will not be evaluated. This safe navigation can be used in the method, variable, and property chaining. The part of the expression that is not evaluated can include variable and property chaining.Example 1:Let’s say we have a method that will take the AccountNumber as a parameter and print the AccountName.Before Winter 21 without Safe Navigation, our code will look like – public static void getAccountNameWithoutSafeNavigation(String accountNumber){...
Read More