Java Reference
In-Depth Information
In this case the closure contains a regular expression that matches any repeated lowercase
letter.
Many existing Java applications have extensive domain models. As you can see, Groovy
code can work with them directly, even treating them as POGOs and giving you a poor-
man's search capability.
Now to demonstrate a capability Groovy can add to Java that Java doesn't even support:
operator overloading.
4.2. Implementing operator overloading in Java
So far I've used the fact that both the + and - operators have been overloaded in the
String class. The overloaded + operator in String should be familiar to Java de-
velopers, because it's the only overloaded operator in all of Java; it does concatenation
for strings and addition for numerical values. Java developers can't overload operators
however they want.
That's different in Groovy. In Groovy all operators are represented by methods, like the
plus method for + or the minus method for—. You can overload [ 2 ] any operator by im-
plementing the appropriate method in your Groovy class. What isn't necessarily obvious,
though, is that you can implement the correct method in a Java class, too, and if an instance
of that class is used in Groovy code, the operator will work there as well (see figure 4.3 ) .
2 Incidentally,changingthebehaviorofoperatorsthiswayisnormallycalledoperator overloading ,becausethesame
operator has different behavior in different classes. Arguably, though, what I'm actually doing is operator overrid-
ing . Effectively they're the same thing here, so I'll use the terms interchangeably.
 
Search WWH ::




Custom Search