0

I'm trying to understand and use safe navigation operator . So, this is the original line -

List<Opportunity> oppList = (List<Opportunity>) Database.query(query.toSOQL());
return ( oppList.isEmpty() ) ? null : oppList.get( 0 );

With Safe Navigation this is what i've done -

List<Opportunity> oppList = (List<Opportunity>) Database.query(query.toSOQL());
return oppList ?.oppList.get( 0 );

On trying to save I get this error - Variable does not exist: oppList.

Can someone help in pointing out what am I missing/what wrong i'm doing here?

-Thanks.

1 Answer 1

5

Correct return statement should be return oppList?.get(0)

As stated in the apex dev guide, if the left-hand-side of the chain expression evaluates to null, the right-hand-side is not evaluated. In return oppList?.oppList.get(0), since the list of opportunities oppList is not null, the safe navigation operator is looking for oppList property within the list. Since, the property doesn't exist, it throws variable does not exist error.

1
  • Thanks a lot for the explanation .
    – Sagnik
    Commented Nov 20, 2020 at 11:49

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .