Java Reference
In-Depth Information
Figure 4.3. Groovy operators are implemented as methods, so if the Java class contains the right methods, Groovy
scripts can use the associated operators on their instances.
To demonstrate this I'll create a Java class that wraps a map. A Department contains
a collection of Employee instances and will have a hire method to add them and a
layOff method to remove them (hopefully not very often). I'll implement operator over-
loading through three methods: plus , minus , and leftShift . Intuitively, plus will
add a new employee, minus will remove an existing employee, and leftShift will be
an alternative way to add. All three methods will allow chaining, meaning that they'll re-
turn the modified Department instance.
Here's the Employee class, which is just the Person POJO by another name:
public class Employee {
private int id;
private String name;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public int getId() { return id; }
public void setId(int id) { this.id = id; }
}
Now for the Department class, shown in the following listing, which maintains the em-
ployee collection in a Map keyed to the employee id values.
 
Search WWH ::




Custom Search