top of page

Safe Navigation Operator in Apex (Winter 21 Release)

Salesforce is releasing a brand new important feature in Winter 21 release which is Safe Navigation Operator, it will useful to safely check null pointer exception.


for e.g. following code will throw null pointer exception if Contact is null.


Id contactId = Contact.Id;


to avoid null pointer exception, a null check is required. Above code can written as follows.


if(Contact!=null)

{

Id contactId = Contact.Id;

}


This new feature will let you safely check null pointer exception. Above code can be written with Safe Navigation Operator as follows.


Id contactId = Contact?.Id;


In this statement if Contact is null, then Contact.Id will not evaluated.


More example -


Let suppose Map<String, Account> accountMap = new Map<String, Account>();

Above map contains Account Name as Key and Account Record as value.


you can safely navigate map as follows.


String accNumber = accountMap?.get('xyz')?.AccountNumber;


In this code, first it will check if accountMap is null or not, if accountMap is not null, it will evaluate get method, it will extract AccountNumber only when accountMap contains 'xyz' key.

So this code will eliminate the need of Map.ContainsKey() method as well.

2,512 views1 comment

Recent Posts

See All
bottom of page