Groovy null检查不在列表中的属性上工作

时间:2016-03-09 23:18:48

标签: groovy truthiness

POJO:

  class Item{
    String prop1
    String prop2
    }

我的数据:

List<Item> items = new ArrayList(new Item(prop1: 'something'), new Item(prop1: 'something'))

然后我尝试:

 if(items?.prop2){
    //I thought prop 2 is present
    }

即使prop2在项目列表中的两个项目上都为空,上面的代码返回true,然后进入if语句。

有人可以告诉我为什么吗?

2 个答案:

答案 0 :(得分:2)

问题是items?.prop2返回[null, null]。由于非空列表的评估结果为真......

您应该能够从以下示例中确定您需要的内容:

class Item {
    String prop1
    String prop2
}

List<Item> items = [new Item(prop1: 'something'), new Item(prop1: 'something')]

assert items?.prop2 == [null, null]
assert [null, null] // A non-empty list evaluates to true
assert !items?.prop2.every() // This may be what you're looking for
assert !items?.prop2.any() // Or Maybe, it's this

if(items?.prop2.every()) {
    // Do something if all prop2's are not null
    println 'hello'
}

if(items?.prop2.any()) {
    // Do something if any of the prop2's are not null
    println 'world'
}

答案 1 :(得分:0)

传播列表的.运算符返回相同大小的列表,其中包含您查找的属性的值(在本例中为2个空值的列表)。非空列表评估为true。