Search code examples
groovygroovy-console

Why do I get a MissingPropertyException in the GroovyConsole?


When I execute the following script in the GroovyConsole it gives me a MissingPropertyException but I do not understand why:

def a = 'A'
def b() {
    println a
}
b()

The following exception is thrown:

groovy.lang.MissingPropertyException: No such property: 
    a for class: ConsoleScript18
at ConsoleScript18.b(ConsoleScript18:3)
at ConsoleScript18.run(ConsoleScript18:5)

Solution

  • You need to add a Field annotation to make it work:

    import groovy.transform.Field
    
    @Field
    def a = 'A'
    def b() {
        println a
    }
    b()