I’ve recently become interested in Groovy because of its very cool language enhancements, and ease of use. One of the stated goals is to make ‘writing concise meaningful maintainable code easier‘. I first used it just to write some simple utility scripts, but it in the future I hope to write some full applications (swing and web based) using it to see just how productive it can be.
To get started, I bought the Groovy in Action book. This is very well written and was easy to work through, and covered so much information I think I’ll be going back through it many times.
If you are interested in Groovy, then you should have a look at these resources:
Some more specific references that you’ll need once you start playing with Groovy:
As I was working through the book, I wrote my own sample code to test out the new language features and to help get a grasp on the new syntax. In case you are interested, I’ve included this code below:
/*
Sample Groovy script to demonstrate language features
*/
// semi-colons optional
println('Hello');
println("World")
//
// asserts are enabled by default
println "\n\n### ASSERTS ### "
assert 1==1
//
def value = 2
try {
assert 1==value
assert false
} catch (AssertionError e) {
assert true
}
//
// gstrings
println "\n\n### GSTRINGS ### "
def firstName = "MC"
String lastName = "Hammer"
assert "Hello MC Hammer"=="Hello ${firstName} ${lastName}"
//
String multiline = """This
is a multiline gstring
${lastName} time!"""
assert "This\nis a multiline gstring\nHammer time!"==multiline
//
// everything is an object - no primitives
println "\n\n### OBJECTS ### "
def a = 10
def b = 20
assert a+b==30
//
// notice the language enhancements (java.lang.Number http://groovy.codehaus.org/groovy-jdk.html#cls27)
assert a.plus(b)==30
assert b.minus(a)==10
assert 'java.lang.Integer'==a.getClass().getName()
//
// Ranges
println "\n\n### RANGES ### "
def myRange = 1..5
assert myRange.size()==5
assert myRange.contains(4)
//
// Lists
println "\n\n### Lists ### "
def myList = []
myList += '1'
assert myList == ['1']
myList += ['2','3']
assert ["1","2","3"] == myList
//
def otherList = ['2']
assert ["2"] == myList.grep(otherList)
//
// Closures
println "\n\n### CLOSURES ### "
// standard java (can't use standard for loop)
/*
for(Iterator i = myList.iterator(); i.hasNext();) {
System.out.println(i.next());
}
*/
// standard java (using while loop)
String result1 = ''
Iterator i = myList.iterator();
while(i.hasNext()) {
result1+=(i.next());
}
assert '123'==result1
//
// groovy
String result2 = ''
myList.each { item -> result2+=item }
assert '123'==result2
//
String result3 = ''
myList.each { item -> result3 += item*2 }
assert '112233'==result3
//
class MethodClosureSample {
int limit
//
MethodClosureSample (int limit) {
this.limit = limit
}
//
boolean validate (String value) {
return value.length() <= limit
}
}
//
def MethodClosureSample first = new MethodClosureSample (6) //#1
def MethodClosureSample second = new MethodClosureSample (5) //#1
def Closure firstClosure = first.&validate //#2
def words = ['long string', 'medium', 'short', 'tiny']
// java.util.collection.find(Closure)
assert 'medium' == words.find (firstClosure) //#3
assert 'short' == words.find (second.&validate) //#4
//
// Looping
println "\n\n### LOOPING ### ";
def store = ""
for(x in [1,2,3]) {
store+=x
}
assert store == "123"
//
store=""
for(x in 1..3) {
store+=x
}
assert store == "123"
//
store = ""
(1..3).each { store+=it }
assert store == "123"
//
// CONSTRUCTORS AND PROPERTIES
println "\n\n### CONSTRUCTORS AND PROPERTIES ### "
class MyClass1 {
String name
void setName(String n) {
name = n?.toUpperCase() // NPE safe
}
String toString() {
return "myclass1 -> name : ${name}"
}
}
def c1 = new MyClass1(name: 'MC Hammer')
assert "myclass1 -> name : MC HAMMER" == c1.toString()
assert c1.name == 'MC HAMMER'
assert c1.getName() == 'MC HAMMER' // auto created getter (and setter) only if they don't already exist
c1.setName('BustaRhymes')
assert 'BUSTARHYMES' == c1.@name // direct access to field
//
// protection from Null Pointer Exception
c1.name=null
assert null == c1?.name?.toLowerCase()





