1. Groovy: a Scripting
Language for Java
Charles Anderson
Western Skies Consulting
cander@westernskiesweb.com
2. Outline
• Introduction and Context
• Stupid Pet Tricks
• Using Groovy in a Java project
• Conclusion
• Grails?
3. Introduction
• There are now many dynamic and/or
scripting languages that run on the Java
Platform
• Groovy is a scripting language specifically for
the Java Platform - feature-rich, Java-friendly
• Groovy compiles to Java classes & byte
code - can use all of Java Platform
4. Introduction
• Scripting - don’t have to explicitly compile
• Typing - static or dynamic (optional/duck)
• Mature - version 1.5, 1.6 Beta 2
• Books, websites, commercial backing, JSR
• IDE Support
6. Java or Groovy?
class Book {
private String title;
Book (String theTitle) {
title = theTitle;
}
String getTitle() {
return title
}
}
7. Stupid Pet Tricks
public class Main {
public static void main(...)
System.out.println(“Hello
World”);
}}
println ‘Hello World’
8. More Powerful Switch
switch (x) {
case 0: // single int
case 1..9: // range
case [11,13,17]: // list
case Float: // type check
case ‘cat’: // string
case ~/[A-Z][0-9]/: //regexp
}
9. Groovy Beans
public class MyBean implements
Serializable {
private String myProp;
public String getMyProp()...
public void setMyProp(...)...
}
class MyBean implements Serializable {
String myProp;
}
11. Bob the Builder
writer = new FileWriter(‘bob.html’)
def page = new MarkupBuilder(writer)
page.html{
head { title ‘An HTML Page’ }
body {
h1 ‘The big heading’
form (action:’submit’) {
input(type:’checkbox’, id:’yes’)
input(type:’checkbox’, id:’no’)
}}}
12. Closures
• A closure is a chunk of code that is a first-
class entity/object in the language
• From functional programming
• Can accept parameters and return a value
• Typical Java solution: inner classes, visitor
pattern, template method pattern
13. Exorcising Inner
Classes
t = new Thread(new Runable() {
public void run() {
// some code
}});
t.start();
Thread.start { //some code }
14. Java Iteration
for (Iterator it=coll.iterator();
it.hasNext(); ) {
Item item=(Item)it.next();
//some code
}
for (Item item : coll) {
// some code
}
17. using Groovy
• Little development tasks - automation
• Can script COM and Windows
• Experiments and spiking
• Testing - unit tests, data loading, scaffolding
18. Conclusion
• Groovy is a dynamic scripting language that
is designed specifically for Java
• Lots of “tricks” to make life easier, but they
can be introduced gradually
• Groovy is a playground for the future of
Java - e.g., closures, properties
• Questions, job leads, Grails?
19. Grails: Groovy on Rails
• Accelerate and simplify web development
on the Java Platform - but not Java Language
• Deploys as a WAR file
• MVC structure
• Convention over configuration
• Uses Spring and Hibernate under covers