Create
Learn
Share

Groovy

rename
Updated 2007-01-14 00:24

Summary

Memorize keywords, tips and code snippets for Groovy, the Java-based scripting language.

Basics

QuestionAnswer
print a stringprintln "hi"
run a groovy script (from the command-line)groovy hi.groovy
string with variable"hi ${s}"
string with expression"hi ${1 + 2}"
define a variabledef s
multi-line string"""foo
bar"""
assert statementassert s == "foo"
memorize

Conventions used on this page

Several example variable names are used, for brevity. Assume the following variables have been defined:
String s, List l, Map m, File f, Object o (example misc object)
Groovy code has access to almost all standard Java classes and methods but I haven't, of course, listed them all here.

Terms / Things to remember

Question Answer
closureblock of code passed as a parameter
itexplicit variable passed to closure (if none are defined)
groovy-starter.conf (in conf/ dir)file to list jars in
GroovletGroovy-ized servlet
GSPGroovy-ized JSP
this.argsaccess command-line args
groovy.codehaus.orgGroovy home page
memorize

Questions

Question Answer
noare semicolons required?
yescan semicolons be used?
yescan groovy code use normal jars?
no in a script
yes in a class
must variables be defined?
nomust method arg types be declared?
nomust exceptions be handled?
yes in a scriptcan code exist outside of a class
memorize

Lists

QuestionAnswer
create a listl = ["foo", "bar"]
append to listl << "third"
iterate through listfor( e in list ) { ... }
join a list (into one string)l.join( "," )
access 2nd element (in a list)l[1]
shorthand for [3, 4, 5]3..5
double listl * 2
memorize

Pages

See also

http://groovy.codehaus.org/Quick+Start"