November 21, 2009

Groovy Goodness: Are You In? (Membership Operator)

Groovy brings some new operators and keywords to the table. One of them is the in keyword or the so-called membership operator. The operator can be called in a conditional context, for example we can use in to test for the existince of a member in a collection. We can write our own implementation by implementing the isCase() method of our class. Or the operator is called in an iterative context, for example in a for loop. Then the iterator() is called. We can write our own implementation for the iterator() to implement in when called in a iterative context.

// *** Conditional context
def list = ['Groovy', 'Java']
assert 'Groovy' in list
assert !('Scala' in list)

// Write our own in implementation.
class MyObject {
    String value
    boolean isCase(ch) { 
def myObj = new MyObject(value: 'Groovy')
assert 'oo' in myObj
assert !('oo' in myObj.value)  // isCase for String invokes equals.
assert 'Groovy' in myObj
assert 'Groovy' in myObj.value
assert !('a' in myObj)

// *** Iterative context
// Use in in a for loop.
def result = ''
for (lang in list ) {
    result += lang
assert 'GroovyJava' == result

class Counter {
    Integer maxValue
    private Integer counter = 0
    Iterator iterator() {
        [hasNext: { counter <= maxValue }, 
         next: { counter++ }] as Iterator
def counter = new Counter(maxValue: 10)
result = '' 
for (c in counter) {
    result += c
assert result == '012345678910'