Groovy: Overriding “Plus” operator in a class with interesting example

26 / Sep / 2012 by Imran Mir 2 comments

Have you ever wondered how to overload “plus” operator in Groovy ? It is as easy as adding toppings to your favourite pizza. Let me explain. Let us taka a class for Pizza:

 

@ToString
class Pizza {
    String name
    List<Topping> toppings
    double price

}

And another for the Topping:

@ToString
class Topping {
    String name
    double price
}

Now to add toppings to the favourite pizza, let us overload the plus operator in Pizza class like this:

//Method with name "plus" will override the "+" operator. It will return a new pizza with the Toppings added.
    Pizza plus(Topping topping) {
        new Pizza(name: name, toppings: toppings + [topping], price: price + topping.price)
    }

Let us order a pizza:

Pizza pizza = new Pizza(name: "Veg Extravaganza Pizza", price: 323.32, toppings: [])

And our favourite toppings as well:

Topping cheeseBurst = new Topping(name: "cheese Burst", price: 80)
Topping extraCheese = new Topping(name: "Extra Cheese", price: 40.43)
Topping jalepenos = new Topping(name: "Jallepenos", price: 50.33)
Topping capsicum = new Topping(name: "capsicum", price: 20.32)

Can’t wait to add them all:

Pizza specialPizza = pizza + cheeseBurst + extraCheese + jalepenos + capsicum

Let us unbox our pizza:

println (specialPizza)
//OUTPUT
/*

Pizza(Veg Extravaganza Pizza, [Topping(cheese Burst, 80.0), Topping(Extra Cheese, 40.43), Topping(Jallepenos, 50.33), Topping(capsicum, 20.32)], 514.4)
*/

Isn’t it mouth watering.

Hope this helps.

 

Imran Mir
imran[at]intelligrape.com

FOUND THIS USEFUL? SHARE IT

comments (2)

  1. nieokapowym

    I’d must test with you here. Which is not something I normally do! I get pleasure from studying a publish that can make people think. Additionally, thanks for allowing me to comment!

    Reply
  2. powyzlabialobys

    I am now not positive the place you are getting your info, however great topic. I needs to spend a while learning much more or figuring out more. Thank you for wonderful info I was looking for this information for my mission.

    Reply

Leave a comment -