groovy入门(二)Codes as data, or closures

本文介绍了Groovy语言中闭包的基础用法及实际应用案例,包括如何定义闭包、使用内置函数collect处理数组、操作文件及字符串等。通过具体实例展示了闭包作为一等公民的强大功能。
groovy入门(二)Codes as data, or closures

首页
http://groovy.codehaus.org/
官方文档
http://groovy.codehaus.org/Tutorial+2+-+Code+as+data,+or+closures

Closures
One of the things that makes Groovy different than most compiled languages is that you can create functions that are first class objects. That is you can define a chunk of code and then pass it around as if it were a string or an integer.
square = { it * it }
square(9)
The curly braces around the expression "it * it" tells the Groovy compiler to treat this expression as code. In the software world, this is called a "closure".
There are some built in functions that take a function like this as an argument. One example is the "collect" method on arrays.
[ 1, 2, 3, 4 ].collect(square)

By default closures take 1 parameter called 'it', you can also create closures with named parameters.
printMap = { key, value -> println key + "=" + value}
['carl':'luohua','kiko':'kangyiyi'].each(printMap)

printList = { println it }
['carl','kiko'].collect(printList)

More Closure Examples
fullString = ""
orderParts = ["BUY", 200, "Hot Dogs", "1"]
orderParts.each {
fullString += it + " "
}
println fullString

First, the closure is interacting with a variable outside itself.
The second thing that is different about this example is that the closure is "anonymous".

Another map example:
myMap = ["asdf": 1 , "qwer" : 2, "sdfg" : 10]
result = 0
myMap.keySet().each( { result+= myMap[it] } )
println result

Dealing with Files
fileDirectory = "d:\\temp\\"
fileName = "test.txt"
file = new File(fileDirectory + fileName)
printFileLine = { println "File line: " + it }
file.eachLine( printFileLine )

file.eachLine

Dealing with strings
stringDate = "2005-07-04"
dateArray = stringDate.split("-")
year = dateArray[0].toInteger()
year = year + 1
newDate = year + "-" + dateArray[1] + "-" + dateArray[2]


references:
http://groovy.codehaus.org/groovy-jdk/
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值