What's the ternary operator in apex?

731    Asked by DavidEdmunds in Salesforce , Asked on Mar 6, 2023

I've seen this somewhere, sometime before but I can't remember how it's used and I can't find anything about it online (Probably because I don't know what to search for). So please help me understand how to use this and also if you link a reference on the official documentation that would be great.


Boolean someVal = true;
String someString = someVal .? 'a value'
// results in someString = 'a value'
Boolean someVal = false;
String someString = someVal .? 'a value'
// results in someString = null
So it looks similar or maybe exactly like this code and I think it returns a null if the condition isn't true and returns 'a value' if the condition is true. 
Answered by Diya tomar
  The thing you're looking for is the safe navigation ternary operator in apex which was introduced in Winter '21 (API v50.0) 

It's the reverse of what you thought it was, ?., and it helps us deal with nulls in a very compact fashion (as opposed to the previous null checks that we had to pepper all over the place).

  Both of your examples would end up holding 'a value', because the variable you're testing has a defined value (false != null).
If that's not quite what you're looking for, then the next match would be the standard ternary operator, which has a syntax of  ?  :  such as Integer myInt = (2 + 2) > 3 ? 1 : -1;.

Your Answer

Interviews

Parent Categories