2

I saw this kind of logic somewhere in an apex code and got curious about how this can be done. The code is a one liner and does variable check and assignment in the same line. It uses the <> operator to check , for example:

String s = if(s<>null,'Hello',null);

The above code is not accurate and gives compiler error. I am unable to remember what was the correct syntax for doing such an assignment and check at the same line. Any idea? THis one liner saves the number of lines to write a if check and then assign value logic.

4

It's called ternary assignment and the syntax is:

String someVariable = someBoolean ? truthyValue : falsyValue;

You can see more info in Understanding Expression Operators:

Operator
? :

Syntax
x ? y : z

Description
Ternary operator (Right associative). This operator acts as a short-hand for if-then-else statements. If x, a Boolean, is true, y is the result. Otherwise z is the result. Note that x cannot be null.

|improve this answer|||||
  • Thanks. Quick response! that I am not even able to accept the answer so soon. – SfdcBat Apr 11 '17 at 22:48
3

It's a simple "ternary operator":

String s2 = s1 != null? 'Hello': null;

This is also sometimes called the "Elvis operator".

The general syntax is:

condition ? trueValue : falseValue;

Note that both trueValue and falseValue must be the same data type (or null), and only one side or the other is evaluated (e.g. if the condition is true, the false side is not evaluated).

|improve this answer|||||
  • 1
    Never heard of that one before! Elvis has left the building... – Adrian Larson Apr 11 '17 at 22:44
  • Good to know :) – SfdcBat Apr 11 '17 at 22:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.