Showing posts with label parlour tricks. Show all posts
Showing posts with label parlour tricks. Show all posts

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; }

@Override
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 Mirror.java 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.