0

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 语句。

有人能告诉我为什么吗?

4

2 回答 2

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'
}
于 2016-03-10T00:38:53.337 回答
0

.扩展列表的运算符返回与您要查找的属性值相同大小的列表(在本例中为 2 个空值的列表)。非空列表评估为真。

于 2016-03-10T00:09:11.303 回答