【问题标题】:Groovy null check not working on a property in the listGroovy null 检查不适用于列表中的属性
【发布时间】:2016-03-09 23:18:47
【问题描述】:

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

谁能告诉我为什么?

【问题讨论】:

    标签: groovy truthiness


    【解决方案1】:

    问题是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'
    }
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 2021-02-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-05
        相关资源
        最近更新 更多