Is there a better way to write this null check and non-empty check in groovy?

I need to do a null / empty check on some code before doing some logic. I have an item below because I feel that !members?.empty incorrect.

Is there a more efficient way to write the following?

 if (members && !members.empty) { // Some Work } 
+80
grails groovy
Jun 23 '13 at 1:15
source share
2 answers

There is truly a Groovier Way.

 if(members){ //Some work } 

does everything if members is a collection. Zero validation as well as empty validation (empty collections are tied to false ). Welcome Groovy True . :)

+162
Jun 23 '13 at 1:18
source share
— -
 !members.find() 

I think the best way to solve this problem right now is with the code above. Works with Groovy 1.8.1 http://docs.groovy-lang.org/docs/next/html/groovy-jdk/java/util/Collection.html#find () . Examples:

 def lst1 = [] assert !lst1.find() def lst2 = [null] assert !lst2.find() def lst3 = [null,2,null] assert lst3.find() def lst4 = [null,null,null] assert !lst4.find() def lst5 = [null, 0, 0.0, false, '', [], 42, 43] assert lst5.find() == 42 def lst6 = null; assert !lst6.find() 
0
May 28 '19 at 13:31
source share



All Articles