zchen
zchen

Reputation: 119

How to run if-else in jexl?

Here are 3 INT parameters:a,b,c. And 1 String parameter:d. Here is code in Java:

if (a>1) return c+d;
if (b<2) return c-d;
if (d.equals("123") return c*d;
return c+1;

How to turn above code to Jexl? I tried many times, including using var. But it always return null.

Upvotes: 2

Views: 7089

Answers (2)

Ondřej Mach
Ondřej Mach

Reputation: 31

I just ran into this problem when I wanted to display an int as a string in DBeaver. I want to keep the database size small, so I store enums as ints. However, I wanted to see the textual value directly in the database. That's why I used this expression to create a virtual column.

MyEnum == 1 ? 'A' : MyEnum == 2 ? 'B' : MyEnum == 3 ? 'C' : 'Undefined'

Upvotes: 1

IvanNik
IvanNik

Reputation: 2027

Probably you use JEXL expression instead of script. You can use only Ternary conditional in expression. if-else, return, for, while should be used in script:

JexlEngine jexl = new JexlBuilder().create();
JexlScript script = jexl.createScript(scriptText);
result = script.execute(context);

See http://commons.apache.org/proper/commons-jexl/reference/syntax.html

From javadoc:

An expression is different than a script - it is simply a reference to a single expression, not to multiple statements. This implies 'if','for','while','var' and blocks '{'... '}'are NOT allowed in expressions.

A script is some valid JEXL syntax to be executed with a given set of JexlContext variables. A script is a group of statements, separated by semicolons. The statements can be blocks (curly braces containing code), Control statements such as if and while as well as expressions and assignment statements.

Upvotes: 5

Related Questions