Simply Groovy (How to gain Competitive Advantage on Weiqi Gao's Friday Java Quiz)
Weiqi Gao runs the popular Friday Java Quiz. He provides puzzles and invites us to ruminate on bed-time reading of the Java Language Specification, or to recall a Java Puzzler that may have been discussed over dinner. (He would be dismayed if he knew that we occasionally just watch TV.) Often, he absolutely forbids us from using the compiler.
Whatever: if you're like me, you take your best, thoughtful guess and then fire up an editor to check. Often, this is rushed, because it would be nice to be the first one to post a comment. All too often, I don't get to the verification stage because it is just too much effort. I only have so many public static void main
s in me.
These days, I just use Groovy's command-line. It gives me an advantage in terms of speed, and it often makes the problem more fun, because I have to formulate it in a different way.
For example, in the latest quiz, Weiqi says that it can't get much simpler.
In Java, the code is (mostly) as simple as possible:
import java.io.*;
public class Foo {
public static void main(String[] args) {
Serializable bar = null;
System.out.println(bar instanceof Serializable);
}
}
Yet with Groovy's
-e
parameter, life is much easier (and faster):
$ groovy -e " Serializable bar = null ; \
println (bar instanceof Serializable) "
The snippet above has 2 cool elements: (a) Groovy auto-imports
java.util.*
and java.io.*
(e.g. Serializable) for you and (b) it will evaluate an expression on the fly. Because Groovy accepts most Java, this is a handy way to beat the masses to the answer of the Friday Java Quiz.More than that, it is a great way to answer many quick questions in Java. I often use it in my team's war room when a question arises.
Note: I'm not sure, but I think that
-e
may have a bug in 1.5+ on a Windows machine. A single statement works fine, but this:
groovy -e " println 'hi' ; println 'there' "
seems to have trouble on a Windows box. Drop a line on your experience.