Groovy – operator overriding
Posted by Prabhu Beeman on July 18, 2008
What do you think will the world without Google will be?
Let us try to represent this using a groovy code and in the process know more about the groovy language.
1: class World {
2: String result = "World";
3:
4: World(){}
5:
6: World minus(Company company) {
7: if(company.getName() == "Google") {
8: result = "No Search!!!No AdSense!!!"
9: }
10: else {
11: result = "Don't Know"
12: }
13: return this;
14: }
15:
16: World minus(String company) {
17: minus(new Company(company))
18: }
19: // This method is called when we try to print the object
20: String toString() {
21: return result;
22: }
23: }
24:
25: class Company {
26: String name
27: Company(String name) {
28: this.name = name
29: }
30: }
31:
Let me explain the code here
We do not have any more semicolons (optional)
Line 6: We have overridden the ‘-’ (minus) operator here, I will explain this later
Line 7: Now where was getName() defined, well getName() and setName(…) method is created for you the moment you create the property (Line 26)
Line 16: That is operator overloading
Alright so here is the final piece of code, let us go ahead and look at it…
1: def ourWorld = new World()
2: def google = new Company("Google")
3: ourWorld - google
Line 1: This is dynamic typing, the compiler takes care of the object type it should be converting to.
We create a world instance and a Company instance.
So when we remove google from ourWorld(Line 4)
ourWorld – google
What do we get??
Result: No Search!!!No Adsense!!!
Even better with the following code
1: def ourWorld = new World()
2: ourWorld – “Google”
Isn’t this amazing. You just subtract Google from ourWorld and you see the result, couldn’t depict better than this.
