Java Reference
In-Depth Information
Because the bytecodes run on the JVM, you can execute Groovy scripts using the
java
command as long as you include the necessary JAR file in your classpath:
> java -cp .;%GROOVY_HOME%\embeddable\groovy-all-2.1.5.jar hello_world
Hello, World!
Executing Groovy
At runtime, Groovy is just another JAR file. As long as the groovy-all JAR file is in the
classpath, Java is perfectly happy to execute compiled Groovy code.
The
groovy
command is used to execute Groovy programs. It can be used with either the
compiled code (similar to the
java
command) or Groovy source. If you use the source,
the
groovy
command first compiles the code and then executes it.
B.2. Variables, numbers, and strings
Groovy is an optionally typed language. Groovy uses classes to define data types, just as
Java does, but Groovy variables can either have a static type or use the
def
keyword.
For example, I'm perfectly free to declare variables of type
int
,
String
, or
Employee
,
using the standard Java syntax:
int x
String name
Employee fred
If I don't know the type of the variable, or I don't care, Groovy provides the keyword
def
:
def arg
Typed vs. untyped variables
When should you use
def
as opposed to the actual type? There's no strict answer, but re-
cently I had a (very mild) Twitter debate about this issue with Dierk Koenig (lead author of
GinA
), Andres Almiray (lead author of
Griffon in Action
and head of the Griffon project),