Groovy不同于其它編譯語言的事情之一是你能創建優先的類對象.意思是說你
能定義一大堆代碼并且可以在里面放string或integer.看看下面的代碼:
這里的it是關鍵字,不能改變.在花括號里面的表達式"it * it"告訴Groovy編譯器把這個表達
式當作代碼來對待.在軟件世界,這個叫做"閉包".在這個例子中,設計者 "it" 是你要給這個函數
賦值的參數.我們像以下方式來訪問:
square(9)
看看結果是什么:81
再試試下面這句:

square =
{(it * it / 2 + 3) /it }
結果:
Result: 4.8333333333
你可能給square賦一值也沒什么意思.這有一些內建函數,你能像這樣做為一個參數
來調用它.來看一下"collect"函數在數組中的例子:
[ 1, 2, 3, 4 ].collect(square)
這個表達式的意思是,用1,2,3,4創建一個數組,然后調用"collect"方法,進入我們上面定義的閉包.collect方法貫穿數組里的每一項,每一項都調用閉包,然后把結果放入一個新數組中.
結果是:
[ 1, 4, 9, 16 ]
你能使用更多的參數閉包,具體可參看
http://groovy.codehaus.org/groovy-jdk.html
默認的閉包帶一個參數"it",你也能創建閉包用自命名參數.例如方法Map.each()
就是一個閉包兩個參數,它綁定了鍵和值.

printMapClosure =
{ key, value -> println key + "=" + value }
[ "yue" : "wu", "lane" : "burks", "sudha" : "saseethiaseeleethialeselan" ].each(printMapClosure)
結果:
yue=wu
lane=burks
sudha=saseethiaseeleethialeselan
還有一些閉包例子:
fullString = ""
orderParts = ["BUY", 200, "Hot Dogs", "1"]

orderParts.each
{
fullString += it + " "
}

println fullString

下面是匿名閉包的例子:
myMap = ["asdf": 1 , "qwer" : 2, "sdfg" : 10]

result = 0

myMap.keySet().each(
{ result+= myMap[it] } )
println result

文件處理:
myFileDirectory = "C:\\temp\\"
myFileName = "myfile.txt"
myFile = new File(myFileDirectory + myFileName)


printFileLine =
{ println "File line: " + it }

myFile.eachLine( printFileLine )

這個例子打印C:\myfile.txt的內容,你可以隨便輸入一些內容進行測試.
字符串處理:
stringDate = "2005-07-04"
dateArray = stringDate.split("-")
year = dateArray[0].toInteger()
year = year + 1
newDate = year + "-" + dateArray[1] + "-" + dateArray[2]
這里和Java語法的差不多了.
注意第三行一定要toInteger().
不然的話+1就成拼湊字符串了.
自己運行一下看看輸出結果吧.