MVEL Quick Start—MVEL Process Control and Advanced Functions (3)

Previous article

Quick Start with MVEL—Explanation of MVEL Basic Syntax (1)

MVEL Quick Start—MVEL Properties and Text Explanation (2)


process control

  In fact, MVEL's expression form is not limited to simple expressions, it also supports process control. Enables us to execute advanced scripts.

if - then - else

  MVEL supports complete C/Java style if else statements, such as:

if (var > 0) {
   System.out.println("这是一个正数");
}
else if (var == 0) { 
   System.out.println("这个数是0");
}
else { 
   System.out.println("这是一个负数");
}

ternary expression

  Ternary expression declarations are also supported in MVEL, such as:

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

  Ternary expressions also support nested forms:

var > 0 ? "Yes" : (var == 0 ? "这个是是0" : "No")

cycle

Foreach

  MVEL also has a very powerful function, which is its foreach loop function. Similar to Java's foreach, MVEL accepts two parameters in parentheses. The first is the variable of the current loop element, and the other is the traversable that you want to loop through. gather.

  for example:

count = 0;
foreach (stu : students) {
   count++;
   System.out.println("Student #" + count + ":" + stu);
}
    
System.out.println("Total people: " + count);

  MVEL also supports changing a string into a traversable object, such as the following writing:

str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

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

  It will output:

[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]

  It can also use an integer as the second parameter, indicating a loop starting from 1 to the set number. Note that it starts from 1! for example:

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

  This example will output:

123456789

  In addition, starting from MVEL2.0 version, it is supported to abbreviate foreach as for, for example:

for (item : collection) { ... }

For loop

  Starting from MVEL2.0, for loops are supported:

for (int i =0; i < 100; i++) { 
   System.out.println(i);
}

Do While, Do Until loop

  do while and do unil loops are also allowed in MVEL, following the same convention as Java, until is the opposite of while. for example:

do { 
   System.out.println("hello world");
} 
while (x != null);

   It has the same meaning as the following code:

do {
   System.out.println("hello world");
}
until (x == null);

Mapping and flattening

  Simply put, mapping is to convert one object into another object according to certain rules. Using simple syntax, you can extract elements from complex objects, helping us to check or perform subsequent operations more conveniently.

  For example, each object in the users collection has a parent, and now you want to get the names of all parents, then you can write like this:

parentNames = (parent.name in users);

  You can even nest them, like:

familyMembers = (name in (familyMembers in users));

type

  MVEL allows users to manually define variables in expressions and also supports obtaining objects from the context.

  Since MVEL is a weakly typed dynamic language, we do not necessarily need to specify their types when declaring variables, but specifying types is also allowed. For example, the following two sentences are both allowed and have the same meaning:

str = "My String";
String str = "My String";

  Different from Java programs, it will automatically provide type conversion capabilities for objects based on context during runtime, such as:

String num = 1;
num == "1"  //true

  For dynamically typed variables, if you want to perform type conversion, you can simply convert it to the type you want by manually setting it.

num = (String) 1;

function definition

  MVEL allows you to define functions using the def or function keywords. Functions are defined in declaration order and cannot be forward referenced. The only exception is functions marked 'within', which may forward-reference another function.

Simple example

  For example, if we want to output ABC, we can define:

def abc() { System.out.println("ABC!"); }

  This defines a simple function called "abc" that takes no arguments. When it is called, "ABC!" is printed to the console. An MVEL-defined function works like any ordinary method call, and resolution prioritizes the MVEL function over the underlying context method.

abc(); // 调用函数

Parameters and return values

  MVEL can receive parameters and return a single return value, such as:

def addTwo(a, b) { 
   a + b;
}

  This function requires two parameters, a and b. It will add the two numbers and return them. Because MVEL follows the last return principle, we do not need to write return explicitly.

val = addTwo(5, 2);
assert val == 10;

  Also note: the return keyword can be used to force a return from a function's internal program flow.

Closure

  MVEL allows closures. However, this feature does not interoperate with native Java methods.

// 定义一个接受参数的函数   
def someFunction(f_ptr) { f_ptr(); }

// 定义变量
var a = 10;

// 传递给函数一个闭包
someFunction(def { a * 10 }); 

lambda expression

  Example: A simple Lambda expression:

threshold = def (x) { x >= 10 ? x : 0 }; 
result = cost + threshold(lowerBound);

  The above example defines a lambda and assigns it to the variable "threshold". Lambdas are essentially functions that can be assigned to variables. They are essentially closures and can be used like this.

* Part of the content refers to the MVEL official website

Guess you like

Origin blog.csdn.net/qq_20051535/article/details/119921999