Pradeep Pillai
Pradeep Pillai

Reputation: 13

Can someone explain Groovy command chain dsl example in documentation... the text got parsed into maps and closures

show = { println it }
square_root = { Math.sqrt(it) }

def please(action) {
  [the: { what ->
    [of: { n -> action(what(n)) }]
  }]
}

// equivalent to: please(show).the(square_root).of(100)

please show the square_root of 100
// ==> 10.0

I understand please(show) returns an object which has a method called the(param) which in turn returns an object which has a method of(param).

what i dont understand is how the line

please show the square_root of 100

got converted to maps and closures after please(show)

Upvotes: 1

Views: 337

Answers (1)

cfrick
cfrick

Reputation: 37063

The key here is to write the code out without the "optional" calls and member access missing. That is:

please(show).the(square_root).of(100)

The way this then was made to work, is to chain the next call by returning a map, with (at least) a key "in the sentence", that again has a closure as value to continue this chain.

So to write that out even more verbose (for one link in the chain):

.getAt('the').call(square_root)

Upvotes: 2

Related Questions