Operator Overloading In Groovy Tuesday, May 30, 2006

I have been doing some Groovy development lately. I just spent a few minutes spinning around a quirky behavior that makes perfect sense to me now but at first had me scratching my head. Take a look at this...


def sqlDate = new java.sql.Date(System.currentTimeMillis())
sqlDate += 2


That code is creating an instance of java.sql.Date and adding 2 days to it. My moment of confusion comes from the fact that after adding the 2 days the sqlDate reference no longer points to a java.sql.Date object but instead points to a java.util.Date object. Hmm... What is going on?

The operator overloading is being inherited into java.sql.Date from java.util.Date. The plus method in java.util.Date is returning a java.util.Date, which makes perfect sense. Since that method is inherited into java.sql.Date and not overridden then when it is invoked it returns a java.util.Date.

Try this...


def sqlDate = new java.sql.Date(System.currentTimeMillis())
println sqlDate.class
sqlDate += 2
println sqlDate.class

6 comments:

Anonymous said...

I'm sure Groovy is a nice little language, but all the cool kids (tm) are playing with Ruby.

Jeff Brown said...

Dan,

Everyone knows that if you are serious about wanting to execute actionable goals while leveraging maximum synergies in the scope of a truly client-centric environment and you wish to achieve future-proof seamlessly integrated development then you need to be proactive about empowering team members by leveraging their respective core competencies around the right framework. With that, it is clear that Groovy leaves Ruby behind.

Anonymous said...

We are discussing this on the Groovy dev list. It may well be unintended behaviour:)
I have been doing work on supporting proper Date arithmetic (e.g. x = d + 2.days + 7.hours). If we fold this into the main distribution then we really want to keep java.sql.Dates as java.sql.Date.

Anonymous said...

You should be happy man. A geek with two different dates, that's like a record :)

Jeff Brown said...

I worked up unit tests and a patch for this which were all committed to the HEAD last night. Now when you increment, decrement, add to or subtract from a java.sql.Date, a java.sql.Date is returned.

viagra online said...

Wow excellent If you don't see carefully you are not able to see it, because it's very confusing to repeat code in one line.
Thanks for sharing.