/* 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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With