您的位置:首页 > 其它

Gradle基础知识——Groovy的闭包

2017-10-17 22:51 731 查看




定义闭包

def closure_name = {
// closure body
}


上面代码定义一个名为 closure_name 的闭包,用途由 closure body 中的代码定义。匿名闭包指不声明闭包变量名,只有闭包方法体
{ //closure body }


无参闭包

def closure_with_no_param = {
println 'hello,world!'
}


执行
closure_with_no_param()
或者
closure_with_no_param.call()
,将输出
hello,world!


含参闭包

def closure_with_param = {
x,y-> println "x plus y is " + (x+y)
}


执行
closure_with_param(1,2)
,结果为
x plus y is 3!


可以设置默认参数值,例如:

def closure_with_param = {
x,y=0-> println "x plus y is " + (x+y)
}


执行
closure_with_param(1)
,结果为
x plus y is 1!


与方法/函数的结合使用

定义闭包

def closure_demo = {
x -> println x
}


定义方法

def method_name(Closure closure_name){
for(int i=0;i<=100;i+=1){
closure_name(i)
}
}


执行
method_name(closure_demo)
或者
method_name closure_demo
,结果输出如下:

1
2
3
...
100


Gradle构建脚本简析

dependencies {
compile group: 'commons-collections', name: 'commons-collections', version: '3.2'
testCompile group: 'junit', name: 'junit', version: '4.+'
}


其中:

dependencies
为方法或函数名,参数为闭包类型

接下来的
{...}
是一个闭包

//这是个闭包
{
compile group: 'commons-collections', name: 'commons-collections', version: '3.2'
testCompile group: 'junit', name: 'junit', version: '4.+'
}


group: 'commons-collections'
group
变量的值设为
commons-collections


compile
为方法/函数

参考文献

https://www.w3cschool.cn/groovy/groovy_closures.html

http://blog.csdn.net/cckevincyh/article/details/75212415



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: