concept statement in category groovy

appears as: statements, statement, statement, statements, The statement
Groovy in Action, Second Edition

This is an excerpt from Manning's book Groovy in Action, Second Edition.

Table 1.1. Commands to execute Groovy

Command

What it does

groovy Starts the processor that executes Groovy scripts. Single-line Groovy scripts can be specified as command-line arguments.
groovysh Starts the groovysh command-line shell, used to execute Groovy code interactively. By entering statements or whole scripts line by line into the shell, code is executed on the fly.
groovyConsole Starts a graphical interface that’s used to execute Groovy code interactively; moreover, groovyConsole loads and runs Groovy script files.
when (condition);
statement;

We’ll look at the list of statements contained in the block statement and find the index of the expression statement wrapping the method call to check if its index is the last one of the block . If the index is the last one, the associated when statement is missing, and we’re instructing the compiler that a compilation error should occur.

As usual, the GDK offers useful methods that we can take advantage of. For example, the findIndexOf() method allows us to find the index of the statement wrapping the when call, in the list of statements of the current block of code . As you realize, the other visitor methods helped us track where we were (current code block and current statement). With the knowledge of the position of the statement in the block, we verify that the call isn’t the last element of the block , otherwise no following statement can be attached to our when call. If this verification fails, we add a compilation error message that the compiler will report! You can check that the error is thrown by temporarily commenting out the last statement of the business rule. In the else part, we’ll continue our implementation with the transformation per se.

What’s left to do? We want to find the statement associated with our when call, wrap it in a closure, and modify the when call to take that closure a second parameter.

We know the index of the when call, so the statement to be attached is the one following when:

def whenCode = currentBlock.statements[idx + 1]

We wrap that code within a ClosureExpression, whose constructor takes two arguments: an array of parameters that the closure can receive, and the statements forming the body of the closure: