Close

Groovy - Operator Overloading

[Last Updated: Aug 11, 2020]

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

Output

Item{name='Laptop, Monitor', price=850.0}

Please find the complete operator to method name list here.

Example Project

Dependencies and Technologies Used:

  • Groovy 2.5.6
  • JDK 9.0.1
Operator Overloading in Groovy Select All Download
  • groovy-operator-overloading-example
    • src
      • Example1OperatorOverloading.groovy

    See Also