Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

  • If System.getProperty("props") is NULL, I want props to be NULL;
  • Else, I want props to be the value of System.getProperty("props")
like image 536
IAmYourFaja Avatar asked Jul 30 '14 14:07

IAmYourFaja


People also ask

How do I check for null objects in Groovy?

In Groovy we can do this shorthand by using the null safe operator (?.). If the variable before the question mark is null it will not proceed and actually returns null for you.

How do I assign a null value in Groovy?

There is no concept of explicitly assigning null in a properties file. The closest you can get is an empty string as you can read here. Or you can simply not specify the key at all.

Is null in Groovy?

In Groovy, there is a subtle difference between a variable whose value is null and a variable whose value is the empty string. The value null represents the absence of any object, while the empty string is an object of type String with zero characters. If you try to compare the two, they are not the same.

Is Empty check in Groovy?

Groovy - isEmpty()Returns true if this List contains no elements.


1 Answers

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.

like image 56
Nathan Hughes Avatar answered Sep 22 '22 09:09

Nathan Hughes