Salesforce: Safe Navigation Operator

safe navigation operator (?.)可将试图对null值进行运算的表达式短路,并返回null而不是引发NullPointerException。

基本语法:
a?.b // Evaluates to: a == null ? null : a.b
如果a为null, 则返回a; 否则返回a.b

例如:
String profileUrl = null;
if (user.getProfileUrl() != null) {
profileUrl = user.getProfileUrl().toExternalForm();
}
可简化为
String profileUrl = user.getProfileUrl()?.toExternalForm();

results = [SELECT Name FROM Account WHERE Id = :accId];
if (results.size() == 0) { // Account was deleted
    return null;
}
return results[0].Name;
可简化为
// New code using the safe navigation operator
return [SELECT Name FROM Account WHERE Id = :accId]?.Name;

也可以进行连续使用:
((T)a1?.b1)?.c1()
相当于
T ref = null;
if (a1 != null) {
ref = (T)a1.b1;
}
result = ref.c1();

posted @ 2020-12-01 17:01  Clsriz  阅读(91)  评论(0编辑  收藏  举报