我需要对集合执行 null 或空检查;我认为这!members?.empty
是不正确的。有没有更时髦的方法来编写以下内容?
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. :)
仅供参考,这种代码有效(你会发现它很丑,这是你的权利:)):
def list = null
list.each { println it }
soSomething()
换句话说,这段代码有空/空检查都无用:
if (members && !members.empty) {
members.each { doAnotherThing it }
}
def doAnotherThing(def member) {
// Some work
}
!members.find()
我认为现在解决这个问题的最好方法是上面的代码。它从 Groovy 1.8.1 http://docs.groovy-lang.org/docs/next/html/groovy-jdk/java/util/Collection.html#find()开始工作。例子:
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()