简体   繁体   中英

Error while using the closure in groovy

I am new too the groovy. I have simple code to learn the groovy closures. My code is

class function1{

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

So, output of the program should like 1,4,9 . But I am getting error as

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

I am not getting how variable square found in static scope.

Thank you

You forgot the def keyword:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM