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?
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
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
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With