Appendix A. Groovy reference

 

It’s not always easy to find the information you want about Groovy, so we’ve incorporated a short reference here that includes useful information in an easily digested form. It focuses on two Groovy features: operator overloading and the extension methods that Groovy adds to the core Java class library.

A.1. Operator overloading

Groovy allows you to support operators on your own classes, such as +, *, <<, and so on. The mechanism for this is straightforward: implement methods with specific names. If you want to support adding two matrices together with the + operator, you can implement plus():

class Matrix {
    ...
    Matrix plus(Matrix other) {
        ...
    }
}

Even if you don’t implement any of the operator methods yourself, it’s important to know the mappings for at least two reasons:

  • API documentation shows the methods of a class. You have to infer from the method name and signature whether or not a class supports a particular operator.
  • Exceptions display the method name when an operator is incorrectly used. The mappings allow you to work out that an operator is the source of a problem.

Table A.1 gives you an extensive list of operators and their corresponding method signatures.

A.2. Groovy JDK methods