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

[groovy] closure (closure as function parameter | code example)

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

List of articles

  • One 、 Closures as function arguments
  • Two 、 Closure as a function parameter code example

One 、 Closures as function arguments


Make a statement fun function , Sure Declare the parameter as Closure<?> Closure type , In this function , Execute closure content ;

Declare functions :

/** *  Define a method  ,  Receive closures as parameters  ,  Execute the closure content in the method  * @param closure * @return */def fun(Closure<?> closure) { 
        closure()}

When calling the above function , It only needs take Closure treat as Parameters Pass to function that will do :

    fun ({ 
            println "Closure 1"    })

If Closure is the last parameter of the function , Sure Omit parenthesis , Write the closure after the function :

    fun { 
            println "Closure 2"    }

Two 、 Closure as a function parameter code example


Complete code example :

/** *  Define a method  ,  Receive closures as parameters  ,  Execute the closure content in the method  * @param closure * @return */def fun(Closure<?> closure) { 
        closure()}static void main(String[] args) { 
        fun ({ 
            println "Closure 1"    })    fun { 
            println "Closure 2"    }}

Execution results :

Closure 1Closure 2

 Insert picture description here

原网站

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