groovy学习之闭包的应用

直接调用或通过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

 

你可能感兴趣的:(groovy)