What’s Groovy?

Groovy is an alternate language for the JVM — alternate meaning that you can use Groovy for Java programming on the Java platform in much the same way you would use Java code. Groovy code combines well with Java code when writing new applications, and can also be used to extend existing ones. Groovy currently is in version 1.5.4 and works on the Java 1.4 and Java 5 platforms, as well as Java 6.

One nice thing about Groovy is that its syntax is very similar to the syntax in the Java language. While Groovy’s syntax was inspired by languages like Smalltalk and Ruby, you can think of it as a simpler, more expressive variation on the Java language. (Ruby is different from Groovy in this regard, because its syntax is quite unlike Java syntax.)

Many Java developers take comfort in the similarity between Groovy code and Java code. From a learning standpoint, if you know how to write Java code, you already kind of know Groovy. The main difference between Groovy and the Java language is that Groovy lets you write less code (sometimes far less!) to accomplish the same tasks you might labor over in your Java code.

As you begin playing with Groovy, you’ll find that it makes everyday programming activities much quicker. You’ll know a lot about Groovy’s syntactic shortcuts by the time you’re done with this tutorial. For now, just consider these highlights:

  • Groovy’s relaxed Java syntax allows you to drop semi-colons and modifiers.
  • Everything in Groovy is public unless you state otherwise.
  • Groovy permits you to define simple scripts without having to define a formal class object.
  • Groovy adds some magical methods and shortcuts on normal everyday Java objects to make them easier to work with.
  • Groovy’s syntax also permits you to drop a variable’s type.

Start with Groovy

  • first, Download a binary distribution of Groovy and unpack it into some file on your local file system
  • set your GROOVY_HOME environment variable to the directory you unpacked the distribution
  • add GROOVY_HOME/bin to your PATH environment variable
  • set your JAVA_HOME environment variable to point to your JDK. On OS X this is /Library/Java/Home, on other unixes its often /usr/java etc. If you’ve already installed tools like Ant or Maven you’ve probably already done this step

You should now have Groovy installed properly. You can test this by typing the following in a command shell:

groovysh

 

Hello World

The prototypical Hello World example in Java code looks something like this:

public class HelloWorld {
      public static void main(String[] args) {
          System.out.println("Hello World!"); } }

Consequently, writing the Hello World program in Groovy is as simple as this:

println "Hello World!

Run this Groovy example

Assuming I’ve saved my code into a file called MyFirstExample.groovy, I can run this example by simply typing

 

c:>groovy MyFirstExample.groovy

That’s all it takes to get the words “Hello World!” printed out on my console.

 

Groovy Grammar Features

No type types

In Java, if you want to declare a String variable, you have to type

String value = "Hello World";

If you think about it, though, the characters to the right of the equals sign already imply that String is the type of the variable value. Accordingly, Groovy permits you to drop the String type variable in front of value and replace it with def.

def value = "Hello World"

In essence, Groovy infers an object’s type by its value.

Ranges in Groovy

A range is a sequence of values. For example, “0..4” denotes the inclusive integers 0, 1, 2, 3, 4. Groovy also supports exclusive ranges, where “0..<4” means 0, 1, 2, 3. You can also create a range of characters: “a..e” is equal to a, b, c, d, e. “a..<e” would be all those values less e.

Ranges for looping

Ranges facilitate looping quite nicely. For instance, your previous for loop incremented an integer from 0 to 4 like so:

for(i = 0; i < 5; i++)

A range would make that for loop cleaner and nicer to read:

def repeat(val){ for(i in 0..5){ println val } }

Default parameter values

Groovy supports default parameter values which allow you to specify a parameter’s default value in the formal definition of a function or method. Callers to the function can opt to omit the parameter and accept the default value.

Using the repeat function from earlier, if you want to provide the option to allow callers to specify a repeat value, you can code it as follows:

def repeat(val, repeat=5){ for(i in 0..<repeat){ println val } }

Calling the function, as follows

repeat("Hello World", 2)
repeat("Goodbye sunshine", 4)
repeat("foo")

results in “Hello World” being printed two times, “Goodbye sunshine” four times, and “foo” the default amount of five times.

Groovy collection

To achieve the instance of a collection in normal Java code, you’d have to do something like this:

Collection<String> coll = new ArrayList<String>();
coll.add("Groovy");
coll.add("Java");
coll.add("Ruby");

But in groovy:

def coll = ["Groovy", "Java", "Ruby"]

Groovy gives you a number of ways to add something to a list of items.you can use the add() method (because the underlying collection is a normal ArrayList type), but there are a number of shortcuts you could also try.

For example, each line in the following code adds something to the underlying collection:

coll.add("Python")
coll << "Smalltalk"
coll[5] = "Perl"

Groovy maps

Maps in the Java language are collections of name-value pairs. So, to create a typical map in your Java code, you have to do something like this:

Map<String, String>map = new HashMap<String, String>();
map.put("name", "Andy");
map.put("VPN-#","45");

Groovy makes working with maps as easy as working with lists — for instance, you could write the Java-based map above in Groovy as

def hash = [name:"Andy", "VPN-#":45]

You can put and get items from this hash using normal Java idioms.

hash.put("id", 23)
hash.get("name") == "Andy"

Hopefully you’ve seen by now that Groovy adds its own magic to any equation; consequently, you can put items into a map using the . notation. If you wanted to add a new name-value pair to the map (say dob and “01/29/76”) you could do it, like so:

hash.dob = "01/29/76"

This is similar in the java code :

map.put("dob","01/29/76")

Certainly the . is more groovy than calling get(), don’t you think?

Closures in Groovy(Important)

Closures are a big topic in the Java world right now, with their likely inclusion in Java 7 still being hotly debated. Some have asked why we need closures in the Java language when they already exist in Groovy. In this section, learn about closures in Groovy. If nothing else, what you learn here will come in handy once closures become a formal part of the Java language syntax.

While you did quite a bit of coding with collections in the previous sections, you’ve yet to actually iterate over one. Of course, you know that Groovy is Java, so you can always grab an instance of the old Java Iterator, if you want, and loop over a collection like so:

def acoll = ["Groovy", "Java", "Ruby"]
for(Iterator iter = acoll.iterator(); iter.hasNext();){
     println iter.next() }

But we can do the same thing use follows code :

def acoll = ["Groovy", "Java", "Ruby"]
acoll.each{
      println it
}
The it variable inside the closure is a keyword that points to the individual value of the outside collection being invoked — it is a default value that can easily be overridden by passing a parameter into the closure. So for instance, the following code does the same exact thing, but uses its own item variable:
def acoll = ["Groovy", "Java", "Ruby"]
acoll.each{  value ->
      println  value
}

And also we can use closure with more ways.

def excite = { word -> return "${word}!!" }

This code is a closure named excite. This closure takes one parameter (named word) and returns a String with the word variable along with two exclamation points. Note the use of substitution within the String instance. Using the ${value}syntax within a String tells Groovy to replace the value of a particular variable within the String itself. Think of this syntax as a handy way to do the equivalent of return word + "!!".

 

Wildcard Character

question mark(?)

def s = obj?.pro
This script is the same with :
if(obj is not None):
   def s = obj.pro
Asterisk(*)
["Java", "Groovy"]*.toUpperCase()
This script is the same with:
"Java".toUpperCase()
"Groovy".toUpperCase()

Leave a Reply

Your email address will not be published. Required fields are marked *

%d bloggers like this: