• How to Use Safe Navigation Operator (?.) in Salesforce Apex | Winter 21 Release Notes

    Published By: salesforcepoint
    Published: Monday, 31 August 2020
    A- A+

    How to Use the Safe Navigation Operator in Apex

    How to use Safe Navigation Operator in Apex Salesforce

    Hello guys, as part of salesforce winter 21 release, salesforce introduced Safe Navigation Operator( (?.) to avoid null pointer exceptions in apex. This is very useful feature for developers. If we need to check something (whether it is a object, map, list..) should not be null then we will write (?.) at the end.  If the left side of the expression(?.) is null, then right side is not evaluated and result will be null.

    Till now we used != null condition to check object is not null like below.

    if (object!= null){
       string s= object.fieldName;
    }

    we can write above code by using safe navigation operator like below
    string s= object?.fieldName;
    



    Example: In this example we have a accountIdAccountMap, it contains account id as key, account record as value. We need to get name of the account.

    string accountName = accountIdAccountMap.get(accId).Name; 
    // this will return null pointer exception if accId not available in the map.
    

    if account not exist on map we will get null pointer exception because we accessing null object for fetching name.

    Traditional approach to avoid above null pointer exception:

    if(accountIdAccountMap.get(accId) != null) {
     accountName = accountIdAccountMap.get(accId).Name;
    }

    OR
    if(accountIdAccountMap.containsKey(accId)) {
     accountName = accountIdAccountMap.get(accId).Name;
    }

    By using Safe Navigation operator:

    string Account Name = accountIdAccountMap.get(accId)?.Name;
    

    if we need to check whether map is not null then we can write

    accountIdAccountMap?.get(accId)?.Name;

  • No Comment to " How to Use Safe Navigation Operator (?.) in Salesforce Apex | Winter 21 Release Notes "