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()
p.with{
 age = 12
 name = 'andre'
 address = 'my address'
 doVeryExpensiveWork()
}

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

println p

More, you can transform code like this:


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

into this one:


//groovy
gcalendar = Calendar.instance
gcalendar.with{
 clear()
 set MONTH, JULY
 set DATE,  19
 set YEAR,  1986
}

assert javaCalendar.time == gcalendar.time

=D

Advertisements

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...