Andrey Hihlovskiy

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

Tag Archives: map

Partial interface implementation in groovy

interface X {
  void a()
  void b()
}

class XAdapter implements X {
  void a() { println 'default implementation of a' }
  void b() { println 'default implementation of b' }
}

def o = [
  a: { println 'overridden implementation of a' }
] as XAdapter

o.a()
o.b()

will output:

overridden implementation of a
default implementation of b

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.