0

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?

JBaruch
  • 22,610
  • 5
  • 62
  • 90

2 Answers2

2

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'
}
Emmanuel Rosa
  • 9,697
  • 2
  • 14
  • 20
0

The . operator that spreads the list returns list of the same size with the value of the property you look for (in this case, list of 2 nulls). Not empty lists evaluate to true.

JBaruch
  • 22,610
  • 5
  • 62
  • 90