The program as data

Groovy troopers

Posted in Groovy by seanp33 on October 27, 2009

Last week I had the pleasure of attending SpringOne 2GX with two of my co-workers. Of the three of us, I was the only noob to the No Fluff Just Stuff conference circuit. What an amazing 4 days. What made this conference so much fun was that you could bounce back and forth between the Spring topics and Groovy/Grails/Griffon topics. I’ll save a more complete description of the sessions I attended for a later post but I found myself on the Groovy side of things most often. Being new to the Groovy language I decided to knock up a test case to validate some assumptions.

One thing that I wanted to understand was the use of named parameters within constructors. What I realized is that if you explicitly define a setter within the class, that setter will be invoked as its named counterpart is passed in on object construction. The order in which the fields are defined within the constructor invocation matters and relates directly to the order in which their corresponding setters will be invoked. So ensure that the setter for constructor parameter n doesn’t refer to constructor parameter n+1 or you’ll see some unhappy nulls:)

class Movie{
    private def title
    def director

    def setTitle(theTitle){
        title = theTitle
        println "$title \t Directed by: $director"
     }

     static void main(String[] args){
         def starshipFullOfNull = new Movie(title:"Startship Troopers", director:"Paul Verhoeven")  
         def starshipFullOfPaul = new Movie(director:"Paul Verhoeven", title:"Startship Troopers")  
    }
}
Follow

Get every new post delivered to your Inbox.