Groovy not in collection
The groovy way to see if something is in a list is to use "in"
if('b' in ['a','b','c'])
However how do you nicely see if something is not in a collection?
if(!('g' in ['a','b','c']))
Seems messy and the "!" is hidden to the casual glance. Is there a more idiomatic groovy way to do this?
Thanks!
Another way to write it is with contains
, e.g.
if (!['a', 'b', 'c'].contains('b'))
It saves the extra level of parentheses at the cost of replacing the operator with a method call.
I think there is no not in
pretty syntax, unfortunately. But you can use a helper variable to make it more readable:
def isMagicChar = ch in ['a', 'b', 'c']
if (!isMagicChar) ...
Or, in this case, you may use a regex :)
if (ch !=~ /[abc]/) ...
You can add new functions:
Object.metaClass.notIn = { Object collection ->
!(delegate in collection)
}
assert "2".notIn(['1', '2q', '3'])
assert !"2".notIn(['1', '2', '3'])
assert 2.notIn([1, 3])
assert !2.notIn([1, 2, 3])
assert 2.notIn([1: 'a', 3: 'b'])
assert !2.notIn([1: 'a', 2: 'b'])