Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if a collection is null or empty in Groovy

Tags:

grails

groovy

People also ask

Is null or empty 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.

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. We could even shorten this statement more but you get the idea.

Is null true in Groovy?

groovy Groovy Truth (true-ness) numbers: a zero value evaluates to false, non zero to true. objects: a null object reference evaluates to false, a non null reference to true.


There is indeed a Groovier Way.

if (members) {
    //Some work
}

does everything if members is a collection. Null check as well as empty check (Empty collections are coerced to false). Hail Groovy Truth. :)


FYI this kind of code works (you can find it ugly, it is your right :) ) :

def list = null
list.each { println it }
soSomething()

In other words, this code has null/empty checks both useless:

if (members && !members.empty) {
    members.each { doAnotherThing it }
}

def doAnotherThing(def member) {
  // Some work
}