Search code examples
groovytruthiness

Groovy null check not working on a property in the list


POJO:

  class Item{
    String prop1
    String prop2
    }

My Data:

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

Then I try:

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

even though the prop2 is null on both items in the items list, above code returns me true and goes inside if statement.

Can someone tell me why?


Solution

  • The problem is items?.prop2 returns [null, null]. And since a non-empty list evaluates to true...

    You should be able to identify what you need from the following example:

    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'
    }