How do I create and access the global variables in Groovy?

In a Groovy script the scoping can be different than expected. That is because a Groovy script in itself is a class with a method that will run the code, but that is all done runtime. We can define a variable to be scoped to the script by either omitting the type definition or in Groovy 1.8 we can add the @Field annotation.

import groovy.transform.Field

var1 = 'var1'
@Field String var2 = 'var2'
def var3 = 'var3'

void printVars() {
    println var1
    println var2
    println var3 // This won't work, because not in script scope.
}

Leave a Comment