Learn Java for Web Development

(Tina Meador) #1

404 APPENDIX B: Introduction to Groovy


The console provides the ability to create, save, load, and execute classes and scripts. Some of the
nice features of the console are undo/redo and the ability to inspect variables. If you have to choose
between using GroovyShell and GroovyConsole, I recommend GroovyConsole.You can also define
classes in scripts and use them right away, as illustrated in Listing B-4.


Listing B-4. Defining a Class in the Script


class HelloWorld {
def hello( name ){
"Hello ${name}!"
}
}
def hw = new HelloWorld()
println hw.hello("Vishal")


   The return type of the method hello is not of a specific type, so you use the
reserved keyword def.
 The string "Hello" is not a simple java.lang.String. It is, in fact, one of the
Groovy features: a GString. These types of strings allow string interpolation,
as explained in the next section.

Groovy supports two kinds of strings: regular Java strings and GStrings. A string in Groovy is an
instance ofjava.lang.String if it is surrounded by single quotes or if it is surrounded by double or
triple quotes with no unescaped dollar sign ($).


Figure B-4. Using GroovyConsole with the output detached

Free download pdf