본문 바로가기

Salesforce/Development

Safe Navigation Operator 안전 탐색 연산자(?.)

728x90

Apex API v50.0 부터 새롭게 추가된 내용입니다.

안전 탐색 연산자(?.)는 null 참조에 대한 명시적이고 순차적인 검사를 대체합니다.
이 연산자는 null 값에 대해 작업을 시도하고 NullPointerException을 throw하는 대신 null을 반환하는 식을 단락시킵니다.

표현식의 왼쪽이 null로 평가되면 오른쪽은 평가되지 않습니다. 안전 탐색 연산자(?.) 메서드, 변수 및 속성 연결, 평가되지 않는 표현식 부분에는 변수 참조, 메소드 참조 또는 배열 표현식이 포함될 수 있습니다.

 

이 예는 null을 확인하는 코드 블록을 대체하는 단일 명령문을 보여줍니다.
// Previous code checking for nulls
String profileUrl = null;
if (user.getProfileUrl() != null) {
   profileUrl = user.getProfileUrl().toExternalForm();
}

// New code using the safe navigation operator
String profileUrl = user.getProfileUrl()?.toExternalForm();

 

이 예는 안전 탐색 연산자를 사용하는 단일 행 SOQL 쿼리를 보여줍니다.
// Previous code checking for nulls
List<Account> 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;

 

특정 경우에는 안전 탐색 연산자를 사용할 수 없습니다.
이러한 방식으로 연산자를 사용하려고 하면 컴파일 중에 오류가 발생합니다.

  • Types and static expressions with dots. For example:
    • Namespaces
    • {Namespace}.{Class}
    • Trigger.new
    • Flow.interview.{flowName}
    • {Type}.class
  • Static variable access, method calls, and expressions. For example:
    • AClass.AStaticMethodCall()
    • AClass.AStaticVariable
    • String.format('{0}', 'hello world')
    • Page.{pageName}
  • Assignable expressions. For example:
    • foo?.bar = 42;
    • ++foo?.bar;
  • SOQL bind expressions.
  • With addError() on SObject scalar fields

참고 : https://developer.salesforce.com/docs/atlas.en-us.228.0.apexcode.meta/apexcode/langCon_apex_SafeNavigationOperator.htm

728x90