syntaxgroovynull-check

How to Groovy-ify a null check?


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

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

Logic is:


Solution

  • 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:

    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.