package com.groovy.test
/**
* 1、闭包是可执行的代码块。它们不需要名称,可以在定义之后执行
* 2、闭包在 Groovy 中频繁出现,但是,通常用于在一系列值上迭代的时候
* 3、因为闭包是一个代码块,所以还能够作为参数进行传递
* 4、闭包在 Groovy 中也是一类对象 — 既可以作为参数传递,也可以放在以后执行
* @author Administrator
*
*/
class Closure {
static void main(args) {
closure4()
}
static closure1() {
def acoll = ["Groovy", "Java", "Ruby"]
for(Iterator iter = acoll.iterator(); iter.hasNext();){
println iter.next()
}
}
/**
* 1、这里闭包是作为each的参数用
* 2、闭包中的 it 变量是一个关键字,指向被调用的外部集合的每个值 — 它是默认值,可以用传递给闭包的参数覆盖它。
* @return
*/
static closure2() {
def acoll = ["Groovy", "Java", "Ruby"]
acoll.each
{
println it
}
acoll.each{ value ->
println value
}
}
/**
* 闭包还允许使用多个参数
* @return
*/
static closure3() {
def hash = [name:"Andy", "VPN-#":45]
hash.each{ key, value ->
println "${key} : ${value}"
}
}
/**
* 1、定义一个闭包excite
* 2、闭包两种调用方式,直接引用或者用.call
* 3、在 String 中使用 ${value}语法将告诉 Groovy 替换 String 中的某个变量的值
* @return
*/
static closure4() {
def excite = { word ->
return "${word}!!"
}
assert "Groovy!!" == excite("Groovy")
assert "Java!!" == excite.call("Java")
}
}