Hi all, my name is Hubert A. Klein Ikkink. Not a very common name, right? To make things easier I just picked the first letters of my firstname and surname and came up with haki. So there you have it, now I am also known as Mr. Haki or mrhaki for short. You can read more blog postings at www.mrhaki.com. I am a passionate Groovy and Java developer based in Tilburg, The Netherlands. My goal is to write clean, elegant, user-centered and high quality software. You can find me on Google+ and Twitter. Hubert is a DZone MVB and is not an employee of DZone and has posted 160 posts at DZone. You can read more from them at their website. View Full User Profile

Groovy Goodness: Multiple Overloaded Operator Methods for Nice API

07.03.2012
| 2074 views |
  • submit to reddit

We saw earlier that Groovy supports Multimethods or multiple dispatch. Groovy will resolve the correct overloaded method to invoke based on the runtime type of the method argument. This is great to use for a clean and simple API for a class.

Suppose we have an Event class with a list of attendees and sessions. We want to use the << operator to add attendees and sessions to an Event object. The following code sample shows how we can implement this in Groovy:

class Event {
    List<Person> attendees = []
    List<Session> sessions = []

    Event leftShift(final Person person) {
        attendees << person
        this
    }
    
    Event leftShift(final Session session) {
        sessions << session
        this
    }  
}
class Session { String title }
class Person { String name }

final Event gr8Conf = new Event()
gr8Conf << new Person(name: 'mrhaki') << new Session(title: /Groovy's Hidden Gems/)

assert gr8Conf.attendees.size() == 1
assert gr8Conf.sessions.size() == 1
assert gr8Conf.attendees[0].name == 'mrhaki'
assert gr8Conf.sessions[0].title == "Groovy's Hidden Gems"

 

 

Published at DZone with permission of Hubert Klein Ikkink, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)