在groovy中使用闭包时出错

在groovy中使用闭包时出错,groovy,Groovy,我也是新来的,非常棒。我有简单的代码来学习groovy闭包。 我的代码是 class function1{ static void main(def args){ square = {it * it} [1,2,3].each(square); } } 因此,程序的输出应该是1,4,9。但我也有错误 org.codehaus.groovy.control.MultipleCompilationEr

我也是新来的,非常棒。我有简单的代码来学习groovy闭包。 我的代码是

class function1{

        static void main(def args){
                square = {it * it}
                [1,2,3].each(square);
        }
}
因此,程序的输出应该是
1,4,9
。但我也有错误

org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
/home/xxx/GroovyTest/example2.groovy: 4: Apparent variable 'square' was found in a static scope but doesn't refer to a local variable, static field or class. Possible causes:
You attempted to reference a variable in the binding or an instance variable from a static context.
You misspelled a classname or statically imported field. Please check the spelling.
You attempted to use a method 'square' but left out brackets in a place not allowed by the grammar.
 @ line 4, column 3.
                square = {it * it}
     ^

/home/xxx/GroovyTest/example2.groovy: 5: Apparent variable 'square' was found in a static scope but doesn't refer to a local variable, static field or class. Possible causes:
You attempted to reference a variable in the binding or an instance variable from a static context.
You misspelled a classname or statically imported field. Please check the spelling.
You attempted to use a method 'square' but left out brackets in a place not allowed by the grammar.
 @ line 5, column 16.
                [1,2,3].each(square)
                  ^

2 errors
我不明白变量square是如何在静态范围内找到的


谢谢

您忘记了
def
关键字:

 static void main(def args){
     def square = {it * it}
     [1,2,3].each(square);
 }

您忘记了
def
关键字:

 static void main(def args){
     def square = {it * it}
     [1,2,3].each(square);
 }

另外,类应该有大写的名称
class Function1
,并且只有
static main(args){
可以在Groovy中使用。因此,类应该有大写的名称
class Function1
,只有
static main(args){
可以在Groovy中使用Groovy@Optimus,@IgorArtamonov,我想补充一点:您只能使用未声明的变量使用时(即不使用
def
或显式键入)。您也可以自己使用。@Optimus,@IgorArtamonov,我想补充一点:在使用时,您只能使用未声明的变量(即不使用
def
或显式键入)。您也可以自己使用。