Using Groovy Categories to override operators
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 4.plus(2)
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:
Continue reading