How to Use the Safe Navigation Operator in Apex
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;
Very clear explanation, thanks!
ReplyDelete