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:

 

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

}
[/java]
And another for the Topping:
[java]
@ToString
class Topping {
String name
double price
}
[/java]
Now to add toppings to the favourite pizza, let us overload the plus operator in Pizza class like this:
[java]
//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)
}
[/java]

Let us order a pizza:
[java]
Pizza pizza = new Pizza(name: "Veg Extravaganza Pizza", price: 323.32, toppings: [])
[/java]

And our favourite toppings as well:
[java]
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)
[/java]

Can’t wait to add them all:
[java]
Pizza specialPizza = pizza + cheeseBurst + extraCheese + jalepenos + capsicum
[/java]

Let us unbox our pizza:
[java]
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)
*/
[/java]

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 Reply

Your email address will not be published. Required fields are marked *