4

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)
Opal
  • 81,889
  • 28
  • 189
  • 210
Michael
  • 4,722
  • 6
  • 37
  • 58

2 Answers2

11

The reason behind that is when you write any thing outside function without declaring any class in groovy it is moved to main function.

So the scope of variable a is limited to function main() which you are trying to access in another function b() of same class. But as there is no property a for class it throws MissingPropertyException.

Vinay Prajapati
  • 7,199
  • 9
  • 45
  • 86
Haider Ali
  • 342
  • 2
  • 11
7

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

import groovy.transform.Field

@Field
def a = 'A'
def b() {
    println a
}
b()
Opal
  • 81,889
  • 28
  • 189
  • 210