First page Back Continue Last page Overview Image

Syntactic sugar: closure

assert li.avg() == 39.5454545455

>>groovy.lang.MissingMethodException: No signature of method: java.util.ArrayList.avg()

No List.avg() ? Let’s make one and add it to the Groovy runtime!

List.metaClass.avg = {

return delegate.size() ? delegate.sum() / delegate.size() : 0

}

assert li.avg() == 39.5454545455