The membership operator (in) can be used to test whether provided value is in the target collection or not. It's equivalent to calling contains() method.
Examples
src/Example1MembershipOpt.groovy
def numbers = [2,4,6,8]
println 2 in numbers
println 3 in numbers
println numbers.contains(2)
Output
true false true
The membership operator can be used for maps as well:
src/Example2MembershipOptForMap.groovy
def numbers = [two: 2, four: 4, six: 6, Eight: 8]
println 'two' in numbers
println 2 in numbers
Output
true false
In fact the membership operator can be used with any object which defines boolean inCase(.....) method. Let's create our own object with this method:
src/Example3MembershipOptCustom.groovy
class Multiple{
int num;
Multiple(int num) {
this.num = num
}
boolean isCase(otherNum){
return otherNum % num == 0
}
}
def multipleOfThree = new Multiple(3);
println 6 in multipleOfThree
println 7 in multipleOfThree