Groovy:if-then语句是否有本地范围?

时间:2012-06-07 13:52:17

标签: groovy if-statement scope

不确定我是否正确询问,但我有以下内容:

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

我收到错误 - 没有这样的属性:为课堂答案......

然而,这有效:

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

这是因为变量在If语句中有局部范围吗?有没有更好的方法来编码或者我只需要首先在If语句之外声明我的所有变量?

3 个答案:

答案 0 :(得分:4)

是的,您必须在外部范围内声明您的变量。

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

有关范围的更多信息: http://groovy.codehaus.org/Scoping+and+the+Semantics+of+%22def%22

答案 1 :(得分:4)

如果这是一个脚本,那么@ 0lukasz0所说的不是100%为真,因为:

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

当变量answer进入当前脚本的绑定时(因为它前面没有def),仍然可以正常工作,因此可以在if之外访问block(上面的脚本打印yes

答案 2 :(得分:0)

您可以使用条件运算符来初始化这样的变量。

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

如果要初始化多个变量,Groovy还支持多次赋值。

def (i, j, k) = x == 1? [ 1, 2, 3 ] : []
println "$i $j $k"