Dark theme | Light theme

December 15, 2009

Groovy Goodness: Groovy Mystic Expressions

With Groovy we can omit parenthesis in some cases, key-value parameters for a method are grouped into a group. If we combine all these features we can come up with some pretty mystic expressions. But it is also perfect for writing DSLs, because it doesn't look like real Java/Groovy code anymore. Here is a small sample of an expression that looks strange at first, but at a second look we can see the structure of method calls:

result = []

// Mystic expressions: (see assert for outcome)
say hello:world {
say hello:world { 

assert "Say 'Hello Groovy world!'" == result[0]
assert "Say 'Hello Java world!'" == result[1]

// Actually we are invoking:
// say([hello: world({ 'Groovy' })])
// say([hello: world({ 'Java' })])
// We notice two methods: save(map) and world(closure).

// The methods:
def world(callable) {
    def result = callable()
    "Hello $result world!"

def say(map) {
    result << "Say '${map.hello}'"