Groovy and the with method

Posted on September 10, 2009. Filed under: groovy |

Groovy has some interesting additions to the well known java sdk. As an example, see groovy additions for Object.

One good example is the with method. The with method receive a closure as a parameter. Inside it, you can configure the object state, set properties and call any method:

class Person{
 int age
 String name
 String address    
 boolean workDone

 def doVeryExpensiveWork(){
 println 'working....'
 workDone = true

 def String toString(){
 return "Person -> age: ${age}, name: ${name}, address: ${address}, workDone: ${workDone} "

def p = new Person()
 age = 12
 name = 'andre'
 address = 'my address'

assert p.age == 12
assert == 'andre'
assert p.address == 'my address'
assert p.workDone

println p

More, you can transform code like this:

Calendar javaCalendar = Calendar.getInstance();
javaCalendar.set(Calendar.MONTH, Calendar.JULY);
javaCalendar.set(Calendar.DATE, 19);
javaCalendar.set(Calendar.YEAR, 1986);
Date time = javaCalendar.getTime();

into this one:

gcalendar = Calendar.instance
 set DATE,  19
 set YEAR,  1986

assert javaCalendar.time == gcalendar.time


Read Full Post | Make a Comment ( None so far )

Recently on André.blog…

Groovy plus camel magic

Posted on August 28, 2009. Filed under: groovy | Tags: |

Blog blog = new Blog()

Posted on August 28, 2009. Filed under: Uncategorized |

Liked it here?
Why not try sites on the blogroll...