Groovy allows us to overload the various operators for our objects.
To accomplish that we need to define a method with specific name which will be called when we will apply the operator.
For example to overload + operator, we need to define method plus():
class Item { private String name; private double price; Item(String name, double price) { this.name = name this.price = price } def plus(Item other) { return new Item(this.name + ", " + other.name, this.price + other.price) } @Override public String toString() { return "Item{" + "name='" + name + '\'' + ", price=" + price + '}'; } } def item1 = new Item("Laptop", 500) def item2 = new Item("Monitor", 350) def item3 = item1 + item2 println item3
Item{name='Laptop, Monitor', price=850.0}
Please find the complete operator to method name list here.
Dependencies and Technologies Used: