7

Not sure if I am asking correctly, but I have something like the following:

def x = 1    
if (x == 1) {
   def answer = "yes"
   }
   println answer

I get the error - No such property: answer for class...

However, this works:

def x = 1
def answer = ''
if (x==1) {
   answer = "yes"
   }
   println answer

Is this because variables have a local scope when they are inside of an If statement? Is there a better way to code this or do I just need to declare all my variables outside of the If statement first?

user1435174
  • 71
  • 2
  • 3

3 Answers3

5

Yes, you have to declare your variables in outer scope.

Principle #1: "A variable is only visible in the block it is defined in 
and in nested blocks".

More on scopes: http://groovy.codehaus.org/Scoping+and+the+Semantics+of+%22def%22

0lukasz0
  • 3,155
  • 1
  • 24
  • 40
4

If this is a script, then what @0lukasz0 says isn't 100% true, as this:

def x = 1
if( x == 1 ) {
  // answer is previously undefined -- note no `def`
  answer = "yes"
}
println answer

Will still work as the variable answer goes into the binding for the current script (as it doesn't have a def infront of it), so is accessible outside the if block (the script above prints yes)

tim_yates
  • 167,322
  • 27
  • 342
  • 338
3

You can use the conditional operator to initialize variables like this.

def x = 1    
def answer = x == 1? "yes" : null
println answer

Groovy also supports multiple assignment if you have more than one variable to initialize.

def (i, j, k) = x == 1? [ 1, 2, 3 ] : []
println "$i $j $k"
Justin Piper
  • 3,154
  • 1
  • 20
  • 14