Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1
Chapter 2

[ 25 ]

The Groovy script engine – groovy


Let's start by writing a Groovy version of the ubiquitous Hello World program. We
can start by creating a file called Hello.groovy, which contains the following code:


public class HelloGroovy {
public static void main(String [] args) {
System.out.println("Hello, World!");
}
}

To any Java developer, this looks strangely like Java code. That's because it is Java
code. In the first instance, Groovy is Java source code compatible. Almost anything
you write in Java is source-level compatible with Groovy. To prove this, let's try and
run the following code as a script from the command line:


$groovy HelloWorld.groovy


Hello, World!


This is interesting, and it is a feature that we can make good use of in the future, but
we are not gaining many of the benefits of Groovy by writing in Java. Let's rewrite
this script to be more Groovy.


Groovy is also a scripting language, so we don't need to write our code within a class
to execute it, and we don't need a static main method either. A lot of useful methods
from the JDK, such as println, are provided as wrapper shortcuts by the Groovy
class DefaultGroovyMethods. Thus, we can rewrite our Hello World program in
one line of code as follows:


println "Hello, World!"

The Groovy script engine also defaults the filename suffix, so the following
command works just as well:


$groovy HelloWorld


Hello, World!


We can also invoke the Groovy script engine and pass it a single statement
to execute:


$groovy -e "println 'Hello, World'"


Hello, World!

Free download pdf