当前位置:网站首页>[groovy] closure (closure call | closure default parameter it | code example)

[groovy] closure (closure call | closure default parameter it | code example)

2022-07-05 04:41:00 Programmer community

List of articles

  • One 、 Call closure
  • Two 、 Closure default parameters it
  • 3、 ... and 、 Code example

One 、 Call closure


perform Closure Variable Of call() Method , You can call the closure ;

        //  Define closure variables         def closure = { 
                println "Hello Closure!"        }        //  Call closure         closure.call()

Execute the above code , Print Hello Closure! ;

direct stay Closure After a variable , Write a bracket , You can also call closures ;

        //  Define closure variables         def closure = { 
                println "Hello Closure!"        }                //  Call closure         closure()

Execute the above code , Print Hello Closure! ;

Two 、 Closure default parameters it


Closure Closure Default OK Receive a default parameter , The parameter variable name is it ,

  • If No parameter passed in , Then it for null ,
  • If Pass in the parameter , The it Variable is the parameter value that should be passed in ;

stay closure() Invocation time , Pass in a parameter , It will be automatically assigned to it Variable ;

        //  Define closure variables         def closure = { 
                println it        }        //  Call closure  ,  And pass in a default parameter         closure("Hello")

The above code will print Hello ;

3、 ... and 、 Code example


Code example :

class Test { 
        static void main(args) { 
            //  Define closure variables         def closure = { 
                println "Hello Closure!"        }                // I.  Print closure type                         //  Print closure variable types         println closure.getClass()                // II.  Call closure                         //  Call closure  1        closure.call()        //  Call closure  2        closure()                // III.  Closure default parameters                         //  Define closure variables         def closure1 = { 
                println it        }        //  Call closure         closure1.call("Hello")        //  Call closure  ,  And pass in a default parameter         closure1("Closure")    }}

Execution results :

class Test$_main_closure1Hello Closure!Hello Closure!HelloClosure

 Insert picture description here

原网站

版权声明
本文为[Programmer community]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202140632099066.html