Annotations really provides a whole new view of programming things. Groovy also provides some of its own annotations one of them is Category. Lets take an example of using it. We create a IntegerUtil class and annotate it with Category.

class IntegerUtil {
    List<Integer> multiples(Integer upto) {
        (1..upto).collect {this * it}

Now the above code made your class any other groovy category class for example Time Category. Now you can use these methods as follows -:

List<Integer> multiples
use(IntegerUtil) {
    multiples = 2.multiples(10)
println multiples  // Output -: [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

It really helps when you want some more helper methods on already existing classes.

Hope it helps
Uday Pratap Singh

Leave a Reply

Your email address will not be published. Required fields are marked *

You May Also Like

Subscribe to our Blog

Get latest articles straight to your inbox. Enter your email address below: