特点:
1:默认参数:it(不传参数时,会有默认参数it.有参数时则没有隐式参数it)
def clouser3={println("hello groovy${it}")}
clouser3(name)//hello groovy3333
2:grovvy中闭包如果是最后一个参数可以不放在括号内,可以直接放在括号外
number.downto(1){ num->result *=num}
3:如果参数只有一个闭包,小括号也可以省略
number.downsd{
num->result *=num
}
package variable
//闭包概念:代码块
//闭包的定义
def clouser={
println('hello groovy')
}
//闭包的调用
clouser.call()//使用call 调用
clouser()//想方法一样调用
//增加参数
def clouser1={String name ->println("hello groovy${name}")}
clouser1.call("222")//hello groovy222
clouser1("222")//hello groovy222
def name="3333"
clouser1(name)//hello groovy3333
def clouser2={String arg1,int age->println("hello groovy${name},age${age}")}
clouser2('lich',233)//hello groovy3333::age233
//默认参数:it(不传参数时,会有默认参数it.有参数时则没有隐式参数it)
def clouser3={println("hello groovy${it}")}
clouser3(name)//hello groovy3333
//返回值,闭包是一定有返回值的
def clouser4={
println('hello groovy')
}
def result=clouser4()
println(result)////null .无定义return时,返回值为null
def clouser5={String aa->
return"hello ${aa}";
}
def result2=clouser5("hahaah")
println(result2)//hello hahaah
网友评论