How to Groovy-ify a null check?

25,007

Typically for null-checking I reach for ?: (elvis operator, returns a default value if the left-hand side is null or resolves to false) or ?. (safe navigation, evaluates to null if left-hand side is null). If you want to set a default value to use when a property is not present you can do this:

def myVar = System.properties['props'] ?: 'mydefaultvalue'

which sets myVar to 'mydefaultvalue' if there is nothing found in System.properties for the key 'props' (or if the value returned resolves to false).

But since the default value in your case is null then

def myVar = System.properties['props']

would do the job as well, because when nothing is found for the given key then null is returned.

The Groovy-ifications here are:

  • prefer single-quoted strings to double-quoted ones if you don't need GroovyString interpolation

  • use indexing-with-brackets syntax for maps and lists (instead of 'get' or 'put')

  • use the shortened property form (without the get prefix) if the getter has no arguments (unlike Java, Groovy implements the universal access principle); System.getProperty(String) is a convenience for Java programmers but it's unneeded in Groovy

  • shorten default-if-null cases with ?:

This idiom found in JavaScript using || :

def myVar = System.properties['props'] || 'mydefaultvalue'

doesn't work in Groovy. The result of a boolean test is a boolean, so myVar gets set to true.

Share:
25,007
IAmYourFaja
Author by

IAmYourFaja

my father is a principal at burgoyne intnl and got me this job programming lisp and development. I aspire to unittesting with a concentration in mobile platforms.

Updated on July 09, 2022

Comments

  • IAmYourFaja
    IAmYourFaja almost 2 years

    Is there a more "Groovy" way to write this Groovy code:

    def myVar=(System.getProperty("props") == null)?
        null : System.getProperty("props")
    

    Logic is:

    • If System.getProperty("props") is NULL, I want props to be NULL;
    • Else, I want props to be the value of System.getProperty("props")
  • Krzysztof Romanowski
    Krzysztof Romanowski almost 10 years
    Or def myVar = System.properties['props'] || 'mydefaultvalue'
  • Nathan Hughes
    Nathan Hughes almost 10 years
    @castus: this seems like a familiar idiom in Ruby iirc, and i expected this to work here too. but in groovy your line results in myVar being set to the boolean value true.
  • Phil Brock
    Phil Brock almost 5 years
    In a build.gradle file you can use this for getting Gradle properties with a default: findProperty('foo') ?: 'bar' The findProperty() method belongs to Project (docs.gradle.org/current/javadoc/org/gradle/api/Project.html‌​) - a top-level object you can interface with directly from your script.