Over a million developers have joined DZone.

Groovy Goodness: Multiple Overloaded Operator Methods for Nice API

· Java Zone

Check out this 8-step guide to see how you can increase your productivity by skipping slow application redeploys and by implementing application profiling, as you code! Brought to you in partnership with ZeroTurnaround.

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"

 

 

The Java Zone is brought to you in partnership with ZeroTurnaround. Check out this 8-step guide to see how you can increase your productivity by skipping slow application redeploys and by implementing application profiling, as you code!

Topics:

Published at DZone with permission of Hubert Klein Ikkink , DZone MVB .

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}