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

I need to store a value in a variable in one method and then I need to use that value from that variable in another method or closure. How can I share this value?


Solution 1:

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.
}

Solution 2:

class Globals {
   static String ouch = "I'm global.."
}

println Globals.ouch

Solution 3:

def i_am_not_global = 100 // This will not be accessible inside the function

i_am_global = 200 // this is global and will be even available inside the 

def func()
{
    log.info "My value is 200. Here you see " + i_am_global
    i_am_global = 400
    //log.info "if you uncomment me you will get error. Since i_am_not_global cant be printed here " + i_am_not_global 
}
def func2()
{
   log.info "My value was changed inside func to 400 . Here it is = " + i_am_global
}
func()
func2()

here i_am_global variable is a global variable used by func and then again available to func2

if you declare variable with def it will be local, if you don't use def its global