直接调用或通过call()方法调用
def adder = {x, y -> return x+y} assert adder(2, 3) == 5 assert adder.call(4, 5) == 9
def benchmark(repeat, Closure worker) { def start = System.currentTimeMillis() repeat.times{worker(it)} def stop = System.currentTimeMillis() return stop - start } def slow = benchmark(10000) {(int) it/2} def fast = benchmark(10000) {it.intdiv(2)} println slow println fast assert slow > fast
通过闭包实现累加
def foo(n) { return {n += it} } def closure = foo(1) assert closure(2) == 3 assert closure(1) == 4