Groovy Gotcha With the Every() Collection Method
Author Brian Swartzfager outlines for us a gotcha when using Groovy's every() method in collections. Read on for details.
Join the DZone community and get the full member experience.
Join For FreeIn the Groovy programming language, every object that implements the Iterable interface (such as List and Map objects) comes with the every() method. The every() method takes a closure as an argument and is supposed to evaluate whether every item in the collection meets the condition set forth in the closure:
assert [ 3, 4 ].every{ element -> element > 2 } //true
assert [ fingerCount: 10, toeCount: 10 ].every{ key, value -> value == 10 } //true
Given that, you might reasonably expect that the every() method would return false when executed against an empty collection. But it doesn't:
assert [].every{ element -> element > 2 } //true
assert [ : ].every{ key, value -> value == 10 } //true
There is a JIRA ticket about this issue: https://issues.apache.org/jira/browse/GROOVY-7207. The initial commenter's guess is probably correct: that the every() method starts with a default return value of true and only becomes false if and when an item in the collection fails the conditional test, so an empty collection fails to affect the default value of true.
Still, it's not what I would have expected, and I was unaware of the behavior until I encountered it for myself.
Published at DZone with permission of Brian Swartzfager, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments