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"