Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy: does if-then statement have a local scope?

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?

like image 993
user1435174 Avatar asked Jun 07 '12 13:06

user1435174


2 Answers

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

like image 110
0lukasz0 Avatar answered Oct 25 '22 09:10

0lukasz0


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)

like image 23
tim_yates Avatar answered Oct 25 '22 10:10

tim_yates