Ad
Ad
Ad
Beginner Dev

Dev Tip 8: Using Ternary Operator in Apex/Salesforce

Pinterest LinkedIn Tumblr

In this post, We will try to understand how to use a ternary operator in salesforce to reduce code. Ternary Operator acts as a short-hand for if-then-else statements.

x ?  y  : z

If x a boolean is true then the result will be y and If x a boolean is false then the result will be z.

Integer result= Condition? Valueone : Valuetwo;

Example(Ternary):

Integer currentmarketPrice = 25000;

Integer priormarketPrice = 15000;

Integer OppAmount = priormarketPrice > 15000 ? currentmarketPrice : priormarketPrice ;

If we do not use a ternary operator then we would have ended up implementing If then else logic with multiple lines of code.

Example(Without Ternary operator/If-else logic):

Integer OppAmount;

Integer currentmarketPrice = 25000;

Integer priormarketPrice = 15000;

If(priormarketPrice > 15000 )

{

OppAmount = currentmarketPrice;

} else {

OppAmount = priormarketPrice;

}

Write A Comment