加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2020-12-14 16:25:43 所属栏目:大数据 来源:网络整理
导读:不确定我是否正确询问,但我有以下内容: def x = 1 if (x == 1) { def answer = "yes" } println answer 我收到错误 – 没有这样的属性:课堂答案…… 但是,这有效: def x = 1def answer = ''if (x==1) { answer = "yes" } println answer 这是因为变量在If
不确定我是否正确询问,但我有以下内容:

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

解决方法

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读