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

3 comments:

Bruno said...

This is weird... Why wouldn`t I be able to access a variable that I have defined in a class inside this class method?

Also, I thought it had become an obbligation to either use the type or the def keyword to declare a variable on the lastest versions.

mrhaki said...

@Bruno: this behaviour is only with scripts, not with classes. So with classes you can access variables in a method in the same class.

Anonymous said...

LADIEDA BITCH.

Post a Comment