groovy-notifications mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From "Eric Holley (JIRA)" <j...@apache.org>
Subject [jira] [Created] (GROOVY-8857) Add various 'object != null' syntactic sugar operators.
Date Fri, 26 Oct 2018 14:23:00 GMT
Eric Holley created GROOVY-8857:
-----------------------------------

             Summary: Add various 'object != null' syntactic sugar operators.
                 Key: GROOVY-8857
                 URL: https://issues.apache.org/jira/browse/GROOVY-8857
             Project: Groovy
          Issue Type: Improvement
          Components: Compiler
    Affects Versions: 3.x
            Reporter: Eric Holley


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 occurs due to the null String and zero
being false in Groovy truth. I find myself have 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:

 
{code:java}
def xyz = abc ??: 'default'{code}
  would be compiled as:

 

 
{code:java}
def xyz = abc != null ? abc : 'default'{code}
 

The second would be a unary '?' operator that would look like:

 
{code:java}
if (?abc) {
   // Do something if abc is not equal null.
}{code}
which would be compiled as:
{code:java}
if (abc != null) {
   // Do something if abc is not equal null.
}{code}
The third would be the non-null Elvis assignment operator:
{code:java}
a ??= 'default'{code}
which would compile as:
{code:java}
a = a != null ? a : 'default'{code}
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.

 

 



--
This message was sent by Atlassian JIRA
(v7.6.3#76005)

Mime
View raw message