Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1

The Groovy Language


[ 52 ]

To see how this works, let's take an example script and compile it with the Groovy
compiler. We can use the GVM tool we encountered in Chapter 2, Groovy Quick Start,
to make Groovy available on the command line:


$gvm use groovy 2.4.4


$groovyc AccountTest.groovy


The following example contains two class definitions and some script that uses
these classes:


// AcountTest.groovy
class Customer {
int id
String name
}

class Account {
int id
double balance
Customer owner
void credit (double deposit) {
balance += deposit
}
String toString() {
"Account id ${id} owner ${owner.name} balance is ${balance}"
}
}
customer = new Customer(id:1,name:"Aaron Anderson")
savings = new Account(id:2, balance:0.00, owner:customer)

savings.credit 20.00
println savings

Compiling the preceding code with groovyc will result in the generation of three
class files: Customer.class, Account.class, and AccountTest.class. If we were
to name our script Customer.groovy or Account.groovy, the Groovy compiler
will see this example as having duplicate class definitions because it is also trying to
generate a class file for us.


This extra, generated, class is the key to what makes a script runnable. The generated
class will have a regular Java main method generated along with a run method.
When we run a Groovy script in a shell script or via the groovy command, we are
invoking the main() method of the generated class, which in turn calls the run
method. The code within the script itself is actually within this run method.


http://www.ebook3000.com
Free download pdf