groovy annotaions « Intelligrape Groovy & Grails Blogs

Posts Tagged ‘ groovy annotaions ’

Groovy Category Annotation

Posted by on July 31st, 2011

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.

@Category(Integer)
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
uday@intelligrape.com
https://twitter.com/meudaypratap
http://in.linkedin.com/in/meudaypratap

Posted in Groovy