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 statements
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
Syntax Note: As of MVEL 2.0, it is now possible to simply abbreviate foreach in the same way it is in Java 5.0, by using the for keyword. For example:
for (item : collection) { ... }
For Loop
MVEL 2.0 implements standard C for-loops:
for (int i =0; i < 100; i++) {
System.out.println(i);
}