Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1
Chapter 4

[ 53 ]

In Java, we are used to the idiom of writing a single class per Java file. The
previous style of coding is common in Groovy when writing standalone
scripts and DSLs. For regular coding circumstances, we make use of
Groovy classes in the same idiom as Java with a single class per Groovy
source file, so the coding style will not be unfamiliar to you.

Another important difference to remember when writing Groovy classes versus
Groovy scripts is that Groovy scripts have a special binding for variable references.
In scripts, we can immediately start using a variable from the point that we initialize
it without having to declare it first. Script variables are stored in this binding scope.
So, we can initialize the previous savings variable with the following line of code:


savings = new Account(id:2, balance:0.00, owner:customer)

This will result in the savings variable being automatically added to the binding
scope. At this point, we make use of savings:


println savings

At this point, savings must be in the binding scope or we will get an error.


If we rewrite the script portion of our preceding example to include a class definition
and a static main method, then savings and customer must be explicitly defined by
using the def keyword, as follows:


class AccountSample {
public static void main (args) {
def customer = new Customer(id:1,name:"Aaron Anderson")
def savings = new Account(id:2, balance:0.00,
owner:customer)

savings.credit 20.00
println savings
}
}

Groovy shorthand


We have seen already that Groovy is source compatible with Java. To be more
script-like, Groovy has some syntax elements that are optional and other syntax
shortcuts that make code easier to read and write. By examining the AccountTest
example, we can see some of these shorthand features in action.

Free download pdf