I need to perform a null or empty check on a collection; I think that !members?.empty
is incorrect. Is there a groovier way to write the following?
if (members && !members.empty) {
// Some Work
}
I need to perform a null or empty check on a collection; I think that !members?.empty
is incorrect. Is there a groovier way to write the following?
if (members && !members.empty) {
// Some Work
}
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. :)
members?.age.max()
blows up with "Cannot invoke method max() on null object" when members is null. You would need members?.age?.max()
–
Dickman members*.age.max()
–
Kile List members = null;
and List members = [ [age: 12], [age: 24], [age: null], null ]
against both the solutions –
Nuristan null
in this way? if(!members){ // do something }
–
Tisatisane !members
if your intention is to do something only when members is null
. See the examples here which showcases how Groovy Truth works. It will be better if you explicitly check for null members == null
–
Kanal 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
}
!members.find()
I think now the best way to solve this issue is code above. It works since 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()
© 2022 - 2024 — McMap. All rights reserved.