Question

i knewt how to add method to metaClass of java.util.List :

java.util.List.metaClass.average={

       return delegate.sum()/delegate.size();
}

and if i have def myList=[new Person(score:1),new Person(score:2)] , i call to new method as following:

 myList.average(); 

However, i want to call it as following :

   myList.average{it.score}

How can i add this method to metaClass to be called as Closure( {} and not ())

Was it helpful?

Solution

You should be able to do:

List.metaClass.average = { Closure c ->
    delegate.sum( c ) / delegate.size()
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top