Safe Navigation Operator in Apex

by Rijwan Mohmmed
safe-navigation-operator-in-apex-techdicer

Hello friends, today we are going to discuss Safe Navigation Operator in Apex Salesforce. First, the Left-Hand-Side of the chain expression is evaluated by the Safe Navigation Operator (?.). If it is NULL then the Right-Hand-Side is evaluated and returns NULL. We can use this operator in variable, method, and property chaining.

Also check this: Salesforce Trigger for Count of Contacts Related to Account

To use the Safe Navigation Operator, we just need to replace the dot (.) with “?.“.

Safe Navigation Operator provides the main advantage of avoiding cluttered code when there are too many null checks and making it look much more verbose.

Code :

SafeNavigationCtrl.cls: Safe Navigation Operator in Apex Salesforce

public class SafeNavigationCtrl {

    public static void WithSafeNavigation(){
        List<Account> accList = [SELECT Id, Type FROM Account LIMIT 1];
        if(accList != null && !accList.isEmpty()){
            System.debug(accList[0]?.Type);
        }
    }

    public static void WithoutSafeNavigation(){
        List<Account> accList = [SELECT Id, Type FROM Account LIMIT 1];
        if(accList != null && !accList.isEmpty()){
            System.debug(accList[0].Type);
        }
    }
}

Reference :

  1. Safe Navigation
What’s your Reaction?
+1
2
+1
0
+1
1
+1
1
+1
2
+1
1

You may also like

Leave a Comment