This post originated from an RSS feed registered with Java Buzz
by dion.
Original Post: Perl Deja Vu with new Groovy Syntax
Feed Title: techno.blog(Dion)
Feed URL: http://feeds.feedburner.com/dion
Feed Description: blogging about life the universe and everything tech
One of the nice things about playing with Groovy is that I get some deja vu now and then, back to my Perl and Python days.
For instance, Jeremy Rayner showed us that a Classic Groovy trick is here in JSR Groovy:
Rather than the boring, repetitive:
Point p = new Point(2,5)
you can now do
Point p = [2,5]
This is because groovy will try to do a coercion of a List into the right type needed for the assignment.
It uses the list to choose the appropriate constructor, then invokes it for you. neat.
This then has the effect in most places, such as setters (e.g. for a property of type Point)
foo.point = [2,5]
and in named parameters
bar.setPointLimits(upper:[7,9], lower:[2,4])
And the really interesting stuff (to me) is that the empty list is coerced into the default constructor.
Date today = []
println "the time at the moment is $today"
is equivalent to
Date today = new Date()
I am not sure how much of a fan I am of taking the list syntax ([ ]) and making it have sideeffects, especially [] == empty constructor, but it does remind me of a pattern that was used a lot in the Perl days.
We used to fake named params by passing in Hashes, or references to Hashes a la:
do_foo(a => "hi", b => 32)
So, I would love to see some syntax to enable me to pass named params in a simple syntax.
Something like:
Point p = [x:1, y:2]
foo.point = [x:1, y:2]
Of if you don't want to hijack the syntax, you can do with a suggestion from John Rose:
Date d = (77, Calendar.JUNE, 28)
or:
Date d = (year:77, month:Calendar.JUNE, day:28)
Basically we are getting rid of the implicit new Foo(), and making an assumption from the type that we set. This is funny, as we have been getting rid of the implicit type all along (and potentially even in C# 3.0 [and therefore Java 7? :)]):
d = new Date(77, Calendar.JUNE, 28)
There are different cases. One for when you are passing in new objects to methods, and the other when you are creating a new object. Also there are the sideeffects of "I want to tell you this type". Worth exploring... not sure how I feel about it all yet!