記住閉包
從 Groovy 1.8 開始,在閉包上增加了一個方便的 memoize()
方法:
// normal closure
def sum = { int x, int y ->
println "sum ${x} + ${y}"
return x + y
}
sum(3, 4)
sum(3, 4)
// prints
// sum 3 + 4
// sum 3 + 4
// memoized closure
def sumMemoize = sum.memoize()
sumMemoize(3, 4)
// the second time the method is not called
// and the result it's take from the previous
// invocation cache
sumMemoize(3, 4)
// prints
// sum 3 + 4