Monday, November 16, 2009

Groovy Shell: A Gentle Introduction to Groovy

Groovy Shell brings to Groovy what irb (Interactive Ruby) and jirb (Interactive JRuby) bring to Ruby and JRuby respectively. I have written about both IRB and JIRB and in this blog post I look more closely at Groovy Shell.

As IRB and JIRB do for Ruby and JRuby, Groovy Shell provides an easy, command line based interactive tool for experimenting with Groovy syntax. This can be easier to use for experimenting with Groovy than writing files to be run in a separate step or trying to pass multiple commands to the Groovy interpreter with the -e option.

Assuming that Groovy has been appropriately installed, it is easy to run Groovy Shell with the groovysh command. Doing so leads to the output shown in the next screen snapshot.

Entering "help" at the Groovy Shell prompt brings up usage information as demonstrated in the next screen snapshot.

At this point, I'll demonstrate via Groovy Shell capabilities that Groovy applies similar to capabilities I demonstrated previously for Ruby and JRuby using IRB and JIRB. The next screen snapshot demonstrates some Groovy math operations in Groovy Shell.

Groovy provides many String operations one might not expect in a language as tied to Java as Groovy is. However, the next screen snapshot proves some of Groovy's string operations that behave similarly to those demonstrated for Ruby and JRuby in my previous writings on IRB and JIRB.

The 2004 JavaOne conference presentation The Groovy Programming Language: Let's Get Groovy includes a nice tip related to use of Groovy Shell. In one of that presentation's slides, Rod Cope and James Strachan demonstrated using Groovy Shell to easily determine the methods available on a particular class. They specifically looked at the File class, but it could be used on any class as shown in the next screen snapshot with File and String.

There is much more that can be done with the Groovy Shell and more information is available in the online Groovy User Guide section Groovy Shell. Some problems previously encountered with Groovy Shell are covered in the Troubleshooting section.

For those who prefer a graphical tool similar to Groovy Shell, the Swing-based Groovy Console or Google App Engine powered browser-based Groovy Web Console is likely to be of great interest.