1. Guillaume Laforge / Groovy Project Manager / SpringSource
Whatās new in Groovy 1.6?
All the novelties of the latest version!
1
2. Guillaume Laforge
Groovy Project Manager ā SpringSource
Working on Groovy since 2003
>
> JSR-241 Spec Lead
Initiator of the Grails web framework
>
Co-author of Groovy in Action
>
Speaker: JavaOne, QCon, JavaPolis/Devoxx,
>
JavaZone, Sun Tech Days, SpringOne/The Spring
Experience, JAX, DSL DevCon, and moreā¦
2
2
3. Whatās new in Groovy 1.6?
Article Published by InfoQ
This presentation was prepared with the examples
>
Iāve used in my article written for InfoQ
http://www.infoq.com/articles/groovy-1-6
>
Read this article for more detailed explanations of
>
all the new features in Groovy 1.6
3
3
5. Groovy in a Nutshell
Simplify the Life of Java Developers
Groovy is a dynamic language for the Java Virtual
>
Machine
With a Meta-Object Protocol
ļ¬
Compiles down to bytecode
ļ¬
Open Source Apache licensed project
>
> Relaxed grammar derived from the Java 5
grammar
Borrowed some good ideas from Smalltalk/Python/
ļ¬
Ruby
Java 5 features out of the box: annotations, generics,
ļ¬
static imports, enumsā¦
Flat learning curve
ļ¬
5
5
6. Features at a Glance
Fully Object-Oriented
>
Joint compiler: seamless Java integration
>
Closures: reusable blocks of code / anon functions
>
Properties: forget about getters and setters
>
Optional typing: your choice!
>
BigDecimal arithmetic by default for floating point
>
Handy APIs
>
ļ¬ XML, JDBC, JMX, template engine, Swing UIs
Strong ability for authoring Domain-Specific Languages
>
ļ¬ Syntax-level ābuildersā
ļ¬ Adding properties to numbers: 10.dollars
ļ¬ Operator overloading: 10.meters + 20.kilometers
6
6
7. A Taste of Groovy ā Take 1
A Normal Java Program
public class HelloWorld {
>
private String name;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public String greet() {
return quot;Hello quot;+ name;
}
public static void main(String[] args) {
HelloWorld helloWorld = new HelloWorld();
helloWorld.setName(quot;Groovyquot;);
System.out.println( helloWorld.greet() );
}
}
7
7
8. A Taste of Groovy ā Take 2
A Valid Groovy Program
public class HelloWorld {
>
private String name;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public String greet() {
return quot;Hello quot;+ name;
}
public static void main(String[] args) {
HelloWorld helloWorld = new HelloWorld();
helloWorld.setName(quot;Groovyquot;);
System.out.println( helloWorld.greet() );
}
}
8
8
9. A Taste of Groovy ā Take 3
A Groovier Program!
class HelloWorld {
>
String name
String greet() { quot;Hello $namequot; }
}
def helloWorld = new HelloWorld(name: quot;Groovyquot;)
println helloWorld.greet()
9
9
10. The Groovy Web Console
A Groovy Playground
Groovy works nicely on Google App Engine
>
You can also deploy Grails applications
ļ¬
You can play with Groovy in the web console
>
http://groovyconsole.appspot.com/
ļ¬
10
10
12. Performance Improvements
Both Runtime & Compile-Time
The Groovyc compiler is 3x to 5x faster
>
With a clever class lookup cache
ļ¬
Certain online micro-benchmarks show
>
150% to 460% increase in performance
compared to Groovy 1.5
Thanks to advanced call-site caching techniques
ļ¬
Beware of micro-benchmarks!
ļ¬
Makes Groovy one of the fastest dynamic
>
languages available
12
12
14. Multiple Assignment
Assign Multiple Variables at Once
Newly defined variables
>
def (a, b) = [1, 2]
ļ¬
assert a == 1
assert b == 2
Assign to existing variables
>
def lat, lng
ļ¬
(lat, lng) = geocode(āParisā)
The classical swap case
>
(a, b) = [b, a]
ļ¬
Extra elements ā not assigned to any variable
>
> Less elements ā null into extra variables
14
14
15. More Optional Return
In if/else and try/catch Blocks
The return keyword is optional for the last expression
>
of a method body
ļ¬ But if/else & try/catch didnāt return any value
def method() { if (true) 1 else 0 }
>
assert method() == 1
def method(bool) {
>
try {
if (bool) throw new Exception(quot;fooquot;)
1
} catch(e) { 2 }
finally {3}
}
assert method(false) == 1
assert method(true) == 2
15
15
16. Annotation Definition
The Missing Bit of Java 5 Support
Groovy support for Java 5 features is now complete
>
with the missing annotation definition
Nothing to show here, itās just normal Java :-)
>
Note that the sole dynamic language
>
supporting annotation isā¦ Groovy
Opens the door to EJB3 / JPA / Spring annotations /
ļ¬
Guice / TestNGā¦
16
16
18. Meta-What?
Meta-Programming
The ability of a language to modify itself
>
Groovy 1.6 introduces AST Transformations
>
Abstract Syntax Tree
ļ¬
Goodbye to a lot of boiler-plate technical code!
>
Two kinds of transformations
>
Global transformations
ļ¬
Local transformations: triggered by annotations
ļ¬
18
18
19. AST Transformations in Groovy 1.6
Implement Patterns through Transformations
Several transformations finds their way
>
@Singleton ā okay, not really a pattern ;-)
ļ¬
@Immutable, @Lazy, @Delegate
ļ¬
@Newify
ļ¬
@Category and @Mixin
ļ¬
@PackageScope
ļ¬
Swingās @Bindable and @Vetoable
ļ¬
Grapeās @Grab
ļ¬
Letās have a look at some of them!
>
19
19
20. @Singleton
(Anti-)Pattern Revisited
The evil Java singleton
>
public class Evil {
ļ¬
public static final Evil instance = new Evil ();
private Evil () {}
Evil getInstance() { return instance; }
}
In Groovy:
>
@Singleton() class Evil {}
ļ¬
Thereās also a Ā« lazy Ā» version
>
@Singleton(lazy = true) class Evil {}
ļ¬
20
20
21. @Immutable
The Immutableā¦ Boiler-Plate Code
To properly implement immutable classes
>
No mutators (state musnāt change)
ļ¬
Private final fields
ļ¬
Defensive copying of mutable components
ļ¬
Proper equals() / hashCode() / toString() for
ļ¬
comparisons or for keys in maps, etc.
In Groovy
>
@Immutable final class Coordinates {
ļ¬
Double lat, lng
}
def c1 = new Coordinates(lat: 48.8, lng: 2.5)
def c2 = new Coordinates(48.8, 2.5)
assert c1 == c2
21
21
22. @Lazy
Not Just for Lazy Dudes!
When you need to lazy evaluate / instantiate
>
complex data structures for class fields, mark them
as @Lazy
class Dude {
ļ¬
@Lazy pets = retriveFromSlowDB()
}
Groovy will handle the boiler-plate code for you
>
22
22
23. @Delegate
Not Just for Managers!
You can delegate to fields of your class
>
Think multiple inheritance
ļ¬
class Employee {
ļ¬
def doTheWork() { quot;donequot; }
}
class Manager {
@Delegate
Employee slave = new Employee()
}
def god = new Manager()
assert god.doTheWork() == quot;donequot;
Damn manager who will get all the praiseā¦
>
23
23
27. @Bindable (1/2)
Event-Driven Made Easy
Speaking of boiler-plate codeā¦ property change listeners
>
import java.beans.PropertyChangeSupport;
>
import java.beans.PropertyChangeListener;
public class MyBean {
private String prop;
PropertyChangeSupport pcs = new PropertyChangeSupport(this);
public void addPropertyChangeListener(PropertyChangeListener l) {
pcs.add(l);
}
public void removePropertyChangeListener(PropertyChangeListener l) {
pcs.remove(l);
}
public String getProp() {
return prop;
}
public void setProp(String prop) {
pcs.firePropertyChanged(quot;propquot;, this.prop, this.prop = prop);
}
}
27
27
28. @Bindable (2/2)
Event-Driven Made Easy
Groovyās solution
>
class MyBean {
ļ¬
@Bindable String prop
}
Interesting in Griffon and Swing builder
>
textField text: bind { myBean.prop }
ļ¬
Also of interest: @Vetoable
>
28
28
29. Griffon
The Swing MVC Framework
Leverages Groovyās SwingBuilder
>
and Grailsā infrastructure
http://griffon.codehaus.org
ļ¬
Donāt miss the next session on!
>
29
29
30. Swing Console Improvements
The console can be run as an applet
>
> Code indentation support
> Script dragān drop
> Add JARs in the classpath from the GUI
> Execution results visualization plugin
> Clickable stacktraces and error messages
Not intended to be a full-blown IDE, but handy
>
30
30
33. ExpandoMetaClass DSL
Less Repetition
EMC is a way to change the behavior of types at runtime
>
Before
>
Number.metaClass.multiply = { Amount amount ->
ļ¬
amount.times(delegate) }
Number.metaClass.div = { Amount amount ->
amount.inverse().times(delegate) }
Now in Groovy 1.6
>
Number.metaClass {
ļ¬
multiply { Amount amount -> amount.times(delegate) }
div { Amount amount ->
amount.inverse().times(delegate) }
}
33
33
34. Runtime Mixins
Inject New Behavior to Types at Runtime
class FlyingAbility {
>
def fly() { quot;I'm ${name} and I fly!quot; }
}
class JamesBondVehicle {
String getName() { quot;James Bond's vehiclequot; }
}
JamesBondVehicle.mixin FlyingAbility
assert new JamesBondVehicle().fly() ==
quot;I'm James Bond's vehicle and I fly!quot;
34
34
36. javax.script.* Scripting APIs
Groovy Scripting Engine Built-In
In Groovy 1.6, the JSR-223 / javax.script.* scripting
>
engine for Groovy is bundled
import javax.script.*
ļ¬
def manager = new ScriptEngineManager()
def engine =
manager.getEngineByName(quot;groovyquot;)
assert engine.evaluate(quot;2 + 3quot;) == 5
To evaluate Groovy scripts at runtime in your
>
application, just drop the Groovy JAR in your
classpath!
36
36
41. OSGi Readiness
The Groovy JAR contains OSGi metadata
>
Can be reused in OSGi containers out-of-the-box
ļ¬
Tutorials on Groovy and OSGi
>
http://groovy.codehaus.org/OSGi+and+Groovy
ļ¬
Will show you how to load Groovy as a service, write,
ļ¬
publish and consume Groovy services, and more
41
41
43. Summary
Just Remember that Groovy Rocks! :-)
Groovy 1.6 provides
>
Important performance gains
ļ¬
Efficient compile-time metaprogramming hooks
ļ¬
New useful features (JMX, javax.script.*, etc.)
ļ¬
A script dependencies system
ļ¬
Various Swing-related improvements
ļ¬
Several runtime metaprogramming additions
ļ¬
Get it now!
>
http://groovy.codehaus.org/Download
ļ¬
43
43