Print
Control Flow

MVEL's power goes beyond simple expressions. In fact, MVEL supports an assortment of control flow operators which will allow you to perform advanced scripting operations.

IF-THEN-ELSE

MVEL supports full, C/Java-style if-then-else blocks. For example:

if (var > 0) {
   System.out.println("Greater than zero!");
}
else if (var == -1) { 
   System.out.println("Minus one!");
}
else { 
   System.out.println("Something else!");
}

TERNARY

Ternary statements are supported just as in Java:

var > 0 ? "Yes" : "No";

And nested ternary statements:

var > 0 ? "Yes" : (var == -1 ? "Minus One!" : "No")

FOREACH

One of the most powerful features in MVEL is it's foreach operator. It is similar to the for each operator in Java 1.5 in both syntax and functionality. It accepts two parameters separated by a colon, the first is the local variable for the current element, and the second is the collection or array to be iterated.

For example:

count = 0;
foreach (name : people) {
   count++;
   System.out.println("Person #" + count + ":" + name);
}
    
System.out.println("Total people: " + count);

Since MVEL treats Strings as iterable objects you can iterate a String (character by character) with a foreach block:

str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

foreach (el : str) {
   System.out.print("[" + el + "]"); 
}

The above example outputs: [A][B][C][D][E][F][G][H][I][J][K][L][M][N][O][P][Q][R][S][T][U][V][W][X][Y][Z]

You can also use MVEL to count up to an integer value (from 1):

foreach (x : 9) { 
   System.out.print(x);
}

Which outputs: 123456789

Powered by Atlassian Confluence