Câu trả lời:
Thực sự có một cách Groovier.
if(members){
//Some work
}
làm mọi thứ nếu memberslà một bộ sưu tập. Kiểm tra rỗng cũng như kiểm tra rỗng (Các bộ sưu tập rỗng bị ép buộc false). Sự thật Hail Groovy . :)
members?.age.max()thổi phồng lên với "Không thể gọi phương thức max () trên đối tượng null" khi các thành viên là null. Bạn sẽ cầnmembers?.age?.max()
List members = null;và List members = [ [age: 12], [age: 24], [age: null], null ]chống lại cả hai giải pháp
!members.find()
Tôi nghĩ bây giờ cách tốt nhất để giải quyết vấn đề này là mã ở trên. Nó hoạt động kể từ Groovy 1.8.1 http://docs.groovy-lang.org/docs/next/html/groovy-jdk/java/util/Collection.html#find () . Ví dụ:
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()
FYI loại mã này hoạt động (bạn có thể thấy nó xấu, đó là quyền của bạn :)):
def list = null
list.each { println it }
soSomething()
Nói cách khác, mã này có các kiểm tra rỗng / rỗng đều vô dụng:
if (members && !members.empty) {
members.each { doAnotherThing it }
}
def doAnotherThing(def member) {
// Some work
}