Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1
Chapter 2

[ 29 ]

The load command allows scripts to be loaded into groovysh from a file. However,
some limitations of the Groovy shell make this problematic. The Groovy shell works
by using an instance of the GroovyShell class to evaluate each line of script in turn.
When we run any Groovy script, the variables local to the script are stored in the
binding object. Variables in the binding object behave exactly like variables that are
in a global scope. Since groovysh evaluates the script piecemeal as it encounters
each line, only variables that find their way into the binding are preserved. So, the
following code works because the message variable is stored in the binding, which is
shared between evaluations:


groovy:000> message = "Hello, World!"


===> Hello, World!


groovy:000> println message


Hello, World!


===> null


groovy:000>


However, this version causes an error as message is now treated as a local variable
and not stored in the binding:


groovy:000> String message = "Hello, World!"


===> Hello, World!


groovy:000> println hello


Unknown property: message


groovy:000>


The Groovy console – groovyConsole


The limited set of commands and crude command-line operations make groovysh
problematic for anything other than trying out single expressions or statements.
A much more useful tool is the Groovy console. The Groovy console is a GUI
editor and runtime environment. You only need to type your Groovy statements
in the top pane and the output gets listed in the bottom pane.


You can launch the Groovy console from the command line with the
following command:


$groovyConsole

Free download pdf