Apex - instruction if elseif else

Un if l'instruction peut être suivie d'une instruction facultative else if...else instruction, qui est très utile pour tester diverses conditions en utilisant un seul if...else if déclaration.

Syntaxe

La syntaxe d'un if...else if...else la déclaration est la suivante -

if boolean_expression_1 {
   /* Executes when the boolean expression 1 is true */
} else if boolean_expression_2 {
   /* Executes when the boolean expression 2 is true */
} else if boolean_expression_3 {
   /* Executes when the boolean expression 3 is true */
} else {
   /* Executes when the none of the above condition is true */
}

Exemple

Supposons que notre société chimique ait des clients de deux catégories - Premium et Normal. En fonction du type de client, nous devons leur offrir des réductions et d'autres avantages tels que le service après-vente et l'assistance. Le programme suivant montre une mise en œuvre de la même chose.

//Execute this code in Developer Console and see the Output
String customerName = 'Glenmarkone'; //premium customer
Decimal discountRate = 0;
Boolean premiumSupport = false;
if (customerName == 'Glenmarkone') {
   discountRate = 0.1; //when condition is met this block will be executed
   premiumSupport = true;
   System.debug('Special Discount given as Customer is Premium');
}else if (customerName == 'Joe') {
   discountRate = 0.5; //when condition is met this block will be executed
   premiumSupport = false;
   System.debug('Special Discount not given as Customer is not Premium');
}else {
   discountRate = 0.05; //when condition is not met and customer is normal
   premiumSupport = false;
   System.debug('Special Discount not given as Customer is not Premium');
}