Andrey Hihlovskiy

Professional blog on groovy, gradle, Java, Javascript and other stuff.

Fun with groovy maps and function call syntax

A function having a Map as first parameter:

void doIt(Map attrs, Object content) {
  println attrs
  println content
}

supports equally valid call syntax variations:

// "classical" call syntax, known from java world
doIt([color: 'red', type: 'fruit'], 'hello!')

// parentheses can be omitted
doIt [color: 'red', type: 'fruit'], 'hello!'

// even square brackets for map can be omitted
doIt color: 'red', type: 'fruit', 'hello!'

// order of map properties does not matter,
// map properties can be intermixed with unnamed parameters.

doIt color: 'red', 'hello!', type: 'fruit'

doIt 'hello!', type: 'fruit', color: 'red'

this effectively allows to implement named parameters in groovy.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: