Details
-
Improvement
-
Status: Open
-
Minor
-
Resolution: Unresolved
-
3.x
-
None
-
None
Description
The Elvis operator is great in that is simplifies your code and makes it easier to read. The problem is that when the referenced object is a String or Number, and you want to use a default value when the object is null, unintended results can occur due to the null String and zero being false in Groovy truth. I find myself having to frequently use more syntactically complex code due this the issue.
My proposal is to introduce some new operators to Groovy to address this:
The first would be variation of the Elvis operator '??:' that would work just like '?:' except that the test for truth would always be 'is the referenced object null'. So, for example:
def xyz = abc ??: 'default'
would be compiled as:
def xyz = abc != null ? abc : 'default'
The second would be a unary '?' operator that would look like:
if (?abc) { // Do something if abc is not equal null. }
which would be compiled as:
if (abc != null) { // Do something if abc is not equal null. }
The third would be the non-null Elvis assignment operator:
a ??= 'default'
which would compile as:
a = a != null ? a : 'default'
This class of operators could be referred to as the 'non-null' operators. I think that they would be a good addition to the new 3.x operators.