Over a million developers have joined DZone.

Groovy Goodness: Multiple Overloaded Operator Methods for Nice API

· Java Zone

Discover how AppDynamics steps in to upgrade your performance game and prevent your enterprise from these top 10 Java performance problems, brought to you in partnership with AppDynamics.

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"



The Java Zone is brought to you in partnership with AppDynamics. AppDynamics helps you gain the fundamentals behind application performance, and implement best practices so you can proactively analyze and act on performance problems as they arise, and more specifically with your Java applications. Start a Free Trial.


Published at DZone with permission of Hubert Klein Ikkink, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}