Tips & Tricks

Pay attention at the type of the variable, many time a bad result is due to this. For example if your expression return a number but the variable is type string (that it's also the default type) then its value is always zero.

The form of the expression it's really important for the computation of a value, especially when in the expression is used the variable itself. Consider the following example:

A field with name Money_Gained, read from the data source, that has an integer value and could be null.

A variable Total1 with the expression
IF(EQUALS($F{Money_Gained}, null), $V{Total1}, $V{Total1}+$F{Money_Gained})
initial value zero, and no calculation function;

A variable Total2 with the expression
$V{Money_Gained} == null ? $V{Total2} : $V{Total2}+$F{Money_Gained}
initial value zero, and no calculation function;

The two expressions seem equivalent: they both add the money gained to the variable when it is not null (remember that if there isn't a calculation function then the value of the expression is assigned to the variable). The check if the Money_Gained has value null it's necessary because the sum of a number with the value null is null. So adding null to Total1 or Total2 changes the variable to null. But even with this check when Money_Gained becomes null for the first time even Total1 is null, instead Total2 has the correct value.

This happens because this two expressions have different interpreters, the first is interpreted by Groovy, the second by Java. The Java behavior is to evaluate the condition and then select the correct branch. On the other hand, Groovy computes the two branches, then evaluates the expression, and finally it returns the correct branch. Doing this adds the null value to Total1 before doing the check, and makes Total1 null. To avoid this, use the variable in the main branch only, for example Total1 could be rewritten as:
$V{Total1} + IF(EQUALS($F{Money_Gained}, null),0,F{Money_Gained}).

The syntax is still interpreted by Groovy, but now the variable is out of the IF branches, so even if they are both evaluated, the variable maintains its value.