130

我需要对集​​合执行 null 或空检查;我认为这!members?.empty是不正确的。有没有更时髦的方法来编写以下内容?

if (members && !members.empty) {
    // Some Work
}
4

3 回答 3

257

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. :)

于 2013-06-23T01:18:19.523 回答
1

仅供参考,这种代码有效(你会发现它很丑,这是你的权利:)):

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

换句话说,这段代码有空/空检查无用:

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

def doAnotherThing(def member) {
  // Some work
}
于 2019-11-11T10:58:27.480 回答
0
!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()
于 2019-05-28T13:31:05.673 回答