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

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/

你可能感兴趣的:(jdk,groovy)