Wednesday, March 26, 2008

Groovy 201: How to Win a Bar Bet on Copy-Paste

A Java program and a Groovy program walk into a bar.

The barkeeper says "Hey fellas.... One check or should I just copy-paste Java's and start removing semi-colons?"

Ha ha! How quaint. (Kinda) Funny, because with Groovy's syntax, you can just copy-paste Java programs into Groovy and start from there. Right?

Whoa Nelly

Well, almost. Some Groovy 101 articles will state this. Sometimes they say "you can copy-paste virtually any Java program..."

The 2%

If you are in a pub or bar, and someone makes the first claim, and you sense that they aren't simply being brief, you should have a ready retort.

You could win some cash, or a drink.

This is not a criticism of Groovy, but there are some differences (on the order of 2% or smaller), as enumerated here on the Groovy website.

The Pub Winner

Here is the example to keep in your head. Consider the following Java program:

public class Mirror {
private String image;

public Mirror(String image) { this.image = image; }

public boolean equals(Object rhs) {
Mirror rhsMirror = (Mirror) rhs;
return this.image.equals( rhsMirror.image );

// TODO: hashCode()

public static void main(String[] args) {
Mirror a = new Mirror("you");
Mirror b = new Mirror("you");

if( a == b ) {
System.out.println(" same object! ");
} else {
System.out.println(" different objects ");
As you know, in Java, this will print "different objects".

If you copy this file from to Mirror.groovy, it will run, even with annotations.

But the output will be different.

The Upshot

Groovy identity is different from Java identity. There is a good write-up on this philosophy on the Groovy site (again, here).

I don't judge, in this case. I simply give facts. Now, go out and win some bar bets.


faith healer said...

Or, if you want an example that does not even compile in Groovy, try using an anonymous inner class. (This is not a criticism of Groovy--just a way to win the bet!)

rhyolight said...

I found out yesterday that there is also no

do {
// statement
} while (expression);

in groovy.

Michael Easter said...

Yep, there are a few things not implemented and new keywords (e.g. 'in').

But I like the identity issue because it is very subtle. The other differences will show up immediately as compiler errors/exceptions.

The identity issue is quiet.