1
/* Hello World in Groovy */
println("Hello world")


int a =  5



if (1 == 1){
    println a
    fcn() //line 11
}

def fcn(){
    println a //line 15
}

This is my Groovy script, which gets the error

Hello world
5
Caught: groovy.lang.MissingPropertyException: No such property: a for class: main
groovy.lang.MissingPropertyException: No such property: a for class: main
    at main.fcn(main.groovy:15)
    at main.run(main.groovy:11)

when executed. Why the variable a is not available within the function fcn?

Ray Zheng
  • 3
  • 2

3 Answers3

1

You can define variable a differently:

Option 1

a = 5

Option 2

import groovy.transform.Field

...
@Field int a = 5

The rational is to define a field in a scope of the script as opposed to the variable defined in the "run method" of the Script and hence not accessible from within other functions.

Consider checking this thread for more information A link to Field annotation document also provides relevant information

Mark Bramnik
  • 39,963
  • 4
  • 57
  • 97
0

Option 3 You can define the fcn as a proper function, which is in Groovy represented by Closure. Then you can access the variables of outer scope:

int a =  5

def fcn = {     
  println a
}

if(true){
  fcn()
}
injecteer
  • 20,038
  • 4
  • 45
  • 89
0

try a = 5 while defining the global variable this should be available in the function fcn.

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

floki91
  • 11
  • 3