Groovy supports operator overloading for a limited set of operators. Each supported operator corresponds to a particular method signature. If a type implements that method, then that operator is effectively overloaded for instances of that type.
The +
operator, for example, corresponds to the plus
method, enabling a.plus(b)
to be substituted with a + b
. And thanks to the wonders of polymorphism, a type can define multiple plus
methods to allow +
to behave differently depending on the type on the right hand side of the operator (e.g. [1] + 2
inserts 2
at the end of the list while [1] + [2]
joins the two lists together, resulting in [1, 2]
for both).
This approach to overloading seemed fairly straightforward until I recently discovered two sister operators that had some interesting twists: ++
and --
, which correspond to the next()
and previous()
methods, respectively.
The first twist is that