Groovy supports operator overloading since the start.
Operator overloading is implemented by an actual method signature that maps to an operator.
For example an object with a plus
method can be used with the +
operator.
There is a list of methods and operators available on the Groovy website.
As long as an object has a method with a name that Groovy understands the corresponding operator can be used in Groovy code.
This is even true for Java objects.
Since Groovy 5 you can use the groovy.transform.OperatorRename
annotation on classes, methods or constructors to map other method names to the Groovy operator overloading method names.
This is very useful for third-party classes that you cannot change, but still want to use simple operators in Groovy code.
You can reassign a method name to the following methods so an operator can be used: plus
, minus
, multiply
, div
, remainder
, power
, leftShift
, rightShift
, rightShiftUnassigned
, and
, or
, xor
, compareTo
.
Suppose you use a class with an add
method and want to use the +
operator for this method.
The following annotation can be used @OperatorRename(plus = 'add')
for a method and inside the method you can use the +
operator instead of the add
method of the class.