首页 > 解决方案 > 不能在函数内访问 Groovy 变量

问题描述

/* Hello World in Groovy */
println("Hello world")


int a =  5



if (1 == 1){
    println a
    fcn() //line 11
}

def fcn(){
    println a //line 15
}

这是我的 Groovy 脚本,它得到了错误

Hello world
5
Caught: groovy.lang.MissingPropertyException: No such property: a for class: main
groovy.lang.MissingPropertyException: No such property: a for class: main
    at main.fcn(main.groovy:15)
    at main.run(main.groovy:11)

执行时。为什么该变量a在函数中不可用fcn

标签: groovy

解决方案


选项 3 您可以将 定义fcn为适当的函数,它在 Groovy 中由 表示Closure。然后您可以访问外部范围的变量:

int a =  5

def fcn = {     
  println a
}

if(true){
  fcn()
}

推荐阅读