I recently ran into a case where I was violating the DRY principle by having to encode part of a string every time I added to it. After some digging I found the solution: Groovy Categories.
A bit of Groovy background
A couple key features of Groovy are that everything is an object and that operators are just syntactic sugar for calling methods on the objects. What’s cool about this is that with Groovy you can override the default behavior of these operators for certain classes. For example,
4 + 2 in Groovy really means
How to implement/override operators in Groovy
Groovy allows you to override a LOT of stuff, including final methods and operators. If I want to override a method on the
String class, all I need to do is:
Notice that it (intentionally) only encodes the second
String. Check out the list of operators and associated methods. This is great, but I need to restrict this to code blocks I so choose. That’s where Groovy Categories come in.
Overriding with Categories
Groovy Categories allow you to add functionality to any class at runtime. This means that you can add in methods to final classes (like
java.lang.String). In this case I just want to override a method instead of adding one.
Note that Groovy defaults to
GStrings, so you can’t just use
How would you make this even more Groovy? Enjoy!