Sei sulla pagina 1di 7

Groovy like an old time movie

1 INTRO
Agile and dynamic general purpose scripting language for the Java Virtual Machine
Compiles straight to Java bytecode so you can use it anywhere you can use Java
Builds upon the strengths of Java but has additional power features inspired by languages like Python,
Ruby and Smalltalk
Intended to extend Java, not replace it
Makes modern programming features (like closures, builders, metaprogramming) available to Java
developers with almost-zero learning curve
Provides the ability to statically type check and statically compile your code for robustness and
performance
Supports Domain-Specific Languages and other compact syntax so your code becomes easy to read and
maintain
Makes writing shell and build scripts easy with its powerful processing primitives, OO abilities and an Ant
DSL
Increases developer productivity by reducing scaffolding code when developing web, GUI, database or
console applications
Simplifies testing by supporting unit testing and mocking out-of-the-box
Seamlessly integrates with all existing Java classes and libraries

2 MAJOR DIFFERENCES BETWEEN JAVA AND GROOVY


BigDecimal Artithmetics by default
Floating point number literals are BigDecimals by default. So when you type 3.14, Groovy won't create a
double or a float, but will instead create a BigDecimal. This might lead people into believing that Groovy
is slow for arithmetics!
If you really want to use floats or doubles, be sure to either define such numeric variables with their
float or double types:
double piDouble = 3.14
float piFloat = 3.14??
or use suffixes:
def piDouble = 3.14d
def pifloat = 3.14f??

Default imports

Some packages and classes are imported by default (you do not have to use import statement to use
them):
- java.io.*
- java.lang.*
- java.math.BigDecimal
- java.math.BigInteger
- java.net.*
- java.util.*
- groovy.lang.*
- groovy.util.

Commons

== means equals on all types. In Java there's a weird part of the syntax where == means equality for
primitive types and == means identity for objects. Since we're using autoboxing this would be very
confusing for Java developers (since x == 5 would be mostly false if x was 5). So for simplicity == means
equals() in Groovy. If you really need the identity, you can use the method "is" like foo.is(bar). This does
not work on null, but you can still use == here: foo==null.
in is a keyword.
int[] a = [1,2,3] instead of int[] a = {1,2,3}; when declaring an array.
For loops (all are correct):
for (int i=0; i < len; i++) {...}
for (i in 0..len-1) {...}
for (i in 0..<len) {...}
len.times {...}
Semicolons are optional. Use them if you like (though you must use them to put several statements on
one line).
The return keyword is optional.
You can use the this keyword inside static methods (which refers to this class).
Methods and classes are public by default.
Protected in Groovy has the same meaning as protected in Java, i.e. you can have friends in the same
package and derived classes can also see protected members.
The throws clause in a method signature is not checked by the Groovy compiler, because there is no
difference between checked and unchecked exceptions.

You will not get compile errors like you would in Java for using undefined members or passing
arguments of the wrong type.

Uncommons
Java programmers are used to semicolons terminating statements and not having closures. Also there
are instance initializers in class definitions. So you might see something like:
class Trial {
private final Thing thing = new Thing ( ) ;
{ thing.doSomething ( ) ; }
}
Many Groovy programmers eschew the use of semicolons as distracting and redundant (though others
use them all the time - it's a matter of coding style). A situation that leads to difficulties is writing the
above in Groovy as:
class Trial {
private final thing = new Thing ( )
{ thing.doSomething ( ) }
}
This will throw a MissingMethodException!
The issue here is that in this situation the newline is not a statement terminator so the following block is
treated as a closure, passed as an argument to the Thing constructor. Bizarre to many, but true. If you
want to use instance initializers in this sort of way, it is effectively mandatory to have a semicolon:
class Trial {
private final thing = new Thing ( ) ;
{ thing.doSomething ( ) }
}
This way the block following the initialized definition is clearly an instance initializer.

New Features not found in Java


-

Closures
native syntax for lists and maps
GroovyMarkup and GPath support
native support for regular expressions
polymorphic iteration and powerful switch statement
dynamic and static typing is supported - so you can omit the type declarations on methods,
fields and variables
you can embed expressions inside strings
lots of new helper methods added to the JDK
simpler syntax for writing beans for both properties and adding event listeners

safe navigation using the ?. operator, e.g. "variable?.field" and "variable?.method()" - no more
nested ifs to check for null clogging up your code

3 THINGS TO REMEMBER
Strings
-

Strings are not Lists. In the JVM java.lang.String does not implement java.util.List.
Arrays are not Lists. In the JVM arrays and java.util.List are quite different. In Groovy we support
both as different types to ensure we interoperate cleanly with Java code, though we try
wherever possible to make them interchangable and appear polymorphic.

Maps
-

Maps override the dot operator, so myMap.size will return null unless you have a value for
map[size]. Use map.size() instead.
In map literals, all keys are interpreted as strings by default! If you want to use a variable or
other literal as a key, use parentheses like so: myMap = [(var1):val, (var2):val]

4 EXAMPLE PROGRAM
Java code (will compile and run in Groovy as well):
public class Hello {
String name;
public void sayHello() {
System.out.println("Hello "+getName()+"!");
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public static void main(String[] args) {
Hello hello = new Hello();
hello.setName("world");
hello.sayHello();
}
}

Groovy is roughly a superset of Java; one difference is that things are public by default. So we can write:
class Hello {
String name;
void sayHello() {
System.out.println("Hello "+getName()+"!");
}
void setName(String name) {
this.name = name;
}
String getName() {
return name;
}
static void main(String[] args) {
Hello hello = new Hello();
hello.setName("world");
hello.sayHello();
}
}

Accessors and mutators are automatically created for your class variables, so we can also shorten the
program by taking those out:
class Hello {
String name;
void sayHello() {
System.out.println("Hello "+getName()+"!");
}
static void main(String[] args) {
Hello hello = new Hello();
hello.setName("world");
hello.sayHello();
}
}

In Groovy, System.out.println can be shortened to just println as a convenience:


class Hello {
String name;
void sayHello() {
println("Hello "+getName()+"!");
}

static void main(String[] args) {


Hello hello = new Hello();
hello.setName("world");
hello.sayHello();
}
}

There's also a difference in how Groovy deals with String objectsusing double quotation marks with
strings allows for variable substitution. Strings with single quotation marks do not:
class Hello {
String name;
void sayHello() {
println("Hello $name!");
}
static void main(String[] args) {
Hello hello = new Hello();
hello.setName('world');
hello.sayHello();
}
}

Groovy also allows dot notation for getting and setting fields of classes, just like Java. Unlike Java, this
will actually go through the getter/setter methods (which, you'll recall, are automatically generated in
our current example):
class Hello {
String name;
void sayHello() {
println("Hello $name!");
}
static void main(String[] args) {
Hello hello = new Hello();
hello.name = 'world';
hello.sayHello();
}
}

Typing information is also optional; instead of specifying a type, you can just use the keyword def. Use
of def is mandatory for methods, but it is optional for parameters on those methods. You should also
use def for class and method variables. While we're at it, let's take out those semicolons; they're
optional in Groovy.
class Hello {
def sayHello(name) {

println("Hello $name!")
}
static def main(args) {
Hello hello = new Hello()
def name = 'world'
hello.sayHello(name)
}
}

Because Groovy is a scripting language, there's automatically a wrapping class (called Script, which will
become very important to us later). This wrapping class means that we can get rid of our own wrapping
class, as well as the main method, like so:
def sayHello(name) {
println("Hello $name!")
}
def name = 'world'
sayHello(name)

Further reading:
http://groovy.codehaus.org/Documentation
http://www.oracle.com/technetwork/articles/java/groovy-1695411.html
http://beta.groovy-lang.org/docs/groovy-2.3.1/html/documentation/#_maps

Potrebbero piacerti anche