Loading...

Friday, November 6, 2009

Groovy Goodness: Variable Scope in Scripts

In Groovy scripts we can define variables with a type or with the def keyword. Or we can leave out any type definition or def keyword. This effects the scope of the variable. If we want to use the variable in a method we must not define it with a type or def. This way the variable is added to the script binding and can be accessed in a method.

String s = 'I am in local scope.'
def i = 42
counter = 0

def runIt() {
    try {
        assert 'I am in local scope.' == s
    } catch (e) {
        assert e instanceof MissingPropertyException
    }
    try {
        assert 42 == i
    } catch (e) {
        assert e instanceof MissingPropertyException
    }
    assert 0 == counter++
}

runIt()

assert 'I am in local scope.' == s
assert 42 == i
assert 1 == counter