Understanding Groovy's Null-Safe Comparison Operators
It's important to know that Groovy's comparison operators == and
!= handle nulls gracefully so you don't have to worry about protecting null
values in equality or inequality comparisons.
Furthermore, the >, >=, <, and
<= operators are also designed to avoid null-related exceptions,
however you need to be conscious of how Groovy treats null in these
order-dependent comparisons. Effectively, a null value is "less than" any
other non-null value in the natural ordering, so for example observe the following comparison
results.
|
Left-Side Expression |
Operator |
Right-Side Expression |
Comparison Result |
|---|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
If you want a comparison to treat a null-valued field with different semantics — for example,
treating a null MaximumOverdraftAmount field as if it were zero (0) like a
spreadsheet user might expect — then use the nvl() function as part of your
comparison logic as shown in the following example:
// Change default comparison semantics for the MaximumOverdraftAmount custom field in
// case its value is null by using nvl() to treat null like zero (0)
if (nvl(MaximumOverdraftAmount,0) < -2000) {
// do something for suspiciously large overdraft amount
}
As illustrated by the table above, without the nvl() function in the
comparison any MaximumOverdraftAmount value of null would
always be less than -2000 — since by default null is less
than everything.