Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy variable cannot be accessed within the function

Tags:

groovy

/* 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?

like image 366
Ray Zheng Avatar asked Nov 14 '25 23:11

Ray Zheng


1 Answers

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

like image 143
Mark Bramnik Avatar answered Nov 17 '25 21:11

Mark Bramnik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!