Friday, June 22, 2012

Groovy Goodness: Multiple Overloaded Operator Methods for Nice API

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
    Event leftShift(final Session session) {
        sessions << session
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"


Andrey Paramonov said...

Nice post as usual. Just small clarification: this code doesn't use multiple dispatch - it works the same way in Java, which doesn't have it - but it does demonstrate how to build clean and simple API in Groovy.

Hubert Klein Ikkink said...

@Andrey Paramonov: Thank you for your comment. I see now that you are right and this sample just uses method overloading. I am keeping the link to the multimethods or multiple dispatch blog post, just as a reference that Groovy supports that.

Post a Comment