【问题标题】:Groovy: does if-then statement have a local scope?Groovy:if-then 语句是否具有本地范围?
【发布时间】:2012-06-08 07:28:49
【问题描述】:

不知道我问的是否正确,但我有类似以下内容:

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 语句之外声明所有变量?

【问题讨论】:

    标签: groovy if-statement scope


    【解决方案1】:

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

    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

    【讨论】:

      【解决方案2】:

      如果这是一个脚本,那么 @0lukasz0 所说的并不是 100% 正确的,如下所示:

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

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

      【讨论】:

        【解决方案3】:

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

        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"
        

        【讨论】:

          猜你喜欢
          • 2017-03-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-05-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多