if

The if keyword executes one of two statement blocks.

Purpose

This statement is used for executing one of two statement blocks in the action part of rules or in functions.

Context

Functions or rule actions

Syntax

if (test) {statement} 
[else {statement}] 

Description

The test can be any valid test, as in the Java™ programming language. If the test returns true, the first statement block is executed and the else block is skipped over. If the test returns false, the first block is skipped over and the statement block following the else keyword is executed. Any IRL statement can be executed within the statement block, as well as arithmetic expressions and method calls. A statement block consists of one or more statements. A single statement does not require the braces ({}). The else keyword and its statement block are optional.

Example

In this example, the rule PromotionLevel provides a client with a promotion depending on the value of the shopping cart and past purchases. The rule has a priority value of 1,000,000. The condition ShoppingCart returns an amount in variable ?a and a client number in variable ?c. The second condition, Client, returns a total amount spent in variable ?t corresponding to the client number equal to ?c. In the action part of the rule, if statements are used to identify which promotion, if any, corresponds to the client.

rule PromotionLevel {
   priority = 1,000,000;
   when {
      ?s:ShoppingCart(?a:amount;?id:clientNumber);
      ?c:Client(clientNumber == ?id; ?t:totalPurchaseToDate);
   }
   then {
      if (?a > 100.0 && ?t > 1000.0)
         insert Promotion() {level = 1;}
      else { if ( ?a > 100.0 ) 
         insert Promotion() {level = 2;}
         else if (?t > 1000.0)
            System.out.println("Dear "+ ?c.name +  
            ", we can offer you a 10% discount on a shopping 
            cart valued at over $100 today.");
      }
   }
};

Three cases are treated:

  • The current shopping cart is valued at over $100 and past purchases have exceeded $1000.

  • The current shopping cart is valued at over $100 and past purchases have not exceeded $1000.

  • The current shopping cart is valued at below $100 and past purchases have exceeded $1000.