Archive for February, 2007

Introduction to Groovy (Part 3)

Wednesday, February 14th, 2007

Closures in Groovy

The concept of a closure in computer programming has been around for a long time, and is arguably a very powerful construct in your applications. While the basics of closures are not hard to understand, I will leave the theory out of this blog post and direct you to the Wikipedia entry for closures for a more detailed description.

Consider this following Java code:

[java]class MyClass {
public int add(int x, int y) {
return x + y;
}
}[/java]

The code above defines a method named add that takes two parameters, adds them together, and returns them. It is a block of code that is named. With closures, you have a block of code that is considered to be anonymous that you can use throughout your application. In other words, it isn’t formally named like the add method above, but it is an anonymous code block that can be assigned to a variable.

The equivalent closure in Groovy would look like this:

[groovy]def add = {x, y -> x + y}[/groovy]

The definition of a closure block looks like this:

[code]{ [parameterList ->] code}[/code]

The parameterList is a comma seperated list of parameters that you will pass into the closure, and it is entirely optional. If you do not define a parameter list, the closure will have one implicit parameter named it that you can use in the closure (and the value of it will be null if you do not pass anything in to the closure).

Also remember than in Groovy you don’t have to specify a return statement. It will automatically return the last evaluated value in the block. This makes for much shorter and easier to read code.

By this time you are probably wondering what the utility of this is, and how it is different than a method or using inner classes in Java. Think about this: With closures, you can assign it to a variable name and pass it around like you would a nomral variable. You are probably thinking, “So?” but this actually introduces a lot of power and flexibility into your programming arsenal.

Let’s take a look at a real Groovy example of the utility of closures. Lists in Groovy have a method called findAll which returns a sublist based on your search criteria. You can pass this a closure to determine your search criteria:

[groovy]["Tim", "Timmy", "John", "Johnny", "Bill"].findAll { it.contains(”Tim”) }[/groovy]

The above example defines an anonymous list and invokes the findAll method. It passes a closure into the findAll method which contains some code. Remember that if you don’t define a parameter list in a closure you can use the it variable, and that is what this is. In this case, it is a String and the findAll method expects you to define your conditions using it.

In addition to findAll, there is an each method on Lists and Maps that executes the closure you pass to it on each element in the collection.

One of the neater aspects of closures is when you use it on primatives. Primatives are autoboxed to their object counterparts in Groovy, so you can do code like this:

[groovy]10.times { println “Hello, world!” }[/groovy]

The Long class has a method called times() which takes a closure as an argument. Whatever the value of the number, it will execute the closure code that many times. Pretty neat, isn’t it?

For more detailed information on closures in Groovy, check out the Groovy documentation on closures. This contains a very in-depth look at closures.

I hope this Introduction to Groovy series has sparked some interest in the language. Groovy really is a fun language to work with and I would encourage any programmer to check it out.

Introduction to Groovy (Part 2)

Tuesday, February 13th, 2007

Groovy Datatypes

Groovy supports all of the basic datatypes that Java supports. So natives such as int, byte, char, long, boolean, and so forth are all present and accounted for. Also classes such as String, Date, etc. are all readily available (some with interesting additions).

Groovy has support for collections and provides very useful shortcuts and additions for using lists and maps. Lists are implemented in Groovy as a java.util.ArrayList, and maps are implemented as java.util.HashMap. You don’t have to use the “new” keyword to create an instance of them.

Lists are created like the following:

[groovy]colors = ["red", "orange", "yellow"]
numbers = [4, 8, 15, 16, 23, 42]
mixed = ["cheese", 4, new Date(), "5"][/groovy]

Notice we did not type the array, nor did we instantiate it the Java way by typing “List colors = new ArrayList();”. By default lists in Groovy are dynamically typed and it knows how to do the right thing based on the data you are passing it. But if you wanted a non-dynamic list, you certainly could. Groovy provides an “as” keyword that makes your list adhere to certain typing conditions.

[groovy]stringList = ["one", "two", "three"] as String[][/groovy]

What would happen if we mixed our data on a non-dynamic list?

[groovy]whoops = ["one", 2, new Date()] as String[]
yikes = ["beef", 3, new Date()] as int[][/groovy]

If you use the first example, whoops, you will find that it seems to work ok–all of those items can be cast as a String. In the second example, however, two of those elements cannot be cast into an Integer so groovy will throw a GroovyCastException. The point of this is to show that you have to be careful with your data when you use a non-dynamic list. It may appear to work on the surface, but it may not be what you intended.

Here is a brief overview of some of the operations you can perform on lists

[groovy]test = [1, 2, 3, 4]
test.get(2) // Gets the element at index 2 (indexes start with 0)
test[2] // Same as above
test.add(5) // Add a new element containing the int 5
test += [6] // Add a new element containing the int 6
test.size() // get the size of the list[/groovy]

Maps are similar to lists, but the data they contain is in a key/value pair. So instead of a numerical index, you can have an object (like a string) that represents the value of the element. Maps are defined using [key:value] and if you are using a string for the key, you don’t have to use quotes around it. Here is an example:

[groovy]myMap = [name:"Tim", age:27, sign:"Aries"][/groovy]

And you have similar methods you can use to access the data:

[groovy]myMap.get(”name”) // Returns “Tim”
myMap.name // Also returns “Tim”
myMap.size() // Gets the size of the map

// Add some data to the map
myMap.put(”some-key”, “someValue”)

// Returns “someValue” - quotes needed because of
// the punctuation in the key
myMap.’some-key’[/groovy]

Looping in Groovy

For the most part, if statements and loops behave the same as they do in Java, so I’m not going to cover them in large detail. If statements, and while loops are exactly the same. Groovy does not have a “do..while” loop so there is no point in covering that. The big difference that you need to understand comes from both the for loop and the switch statement.

The for loop in Groovy is more like the “for-each” loop construct in Java 5. You use it to iterate over elements in a map, list, range, or other type of collection. It is much easier to work with than the C-style for loop. Let’s say you have a map and you want to iterate over the values:

[groovy]map = [name:"Bubba", occupation:"Redneck", talents:"Brain Surgery"]
for (val in map.values()) {
println(val)
}[/groovy]

You can also iterate over ranges if you need something numeric:

[groovy]for (i in 0..9) {
println(i)
}[/groovy]

Another change from Java is the switch statement. It is now versatile and useful to use a switch statement, because you can now use anything for a case:

[groovy]
switch(”Some string”) {
case String.class:
println “I am a String!”
break
case “Some other string”:
println “I won’t get here”
break
default:
println “Default case if no other matches!”
break
}[/groovy]

These are just some of the basic features of Groovy. There is a lot more to learn, and I highly recommend that you check out the documentation on the Groovy homepage if you are seriously interested in learning more about the language.

Introduction to Groovy (Part 1)

Monday, February 12th, 2007

Java developers are now being inundated with a number of scripting and dynamic languages that will run on top of the Java Virtual Machine. One of my favorites (and a big focus of this weblog) is Groovy, an agile dynamic language that looks a lot like Java, but is inspired by other languages like Python, Ruby, and Smalltalk. It introduces concepts that current versions of Java lack such as Closures, dynamic typing, operator overloading, and native lists, maps, hashes, and regular expressions (although Java provides classes for those).

Groovy is a dynamic language, not a scripting language. The code compiles down to Java bytecode instead of being interpreted like a lot of other languages. It is useful for writing web applications, shell scripts, and test cases. In fact, there is tight integration with JUnit for testing.

The code is quite easy. A basic “Hello, world” program in Groovy can look like this:

[groovy]println “Hello, world!”[/groovy]

Whereas in Java, the code looks like this:

[java]class HelloWorld {
public static void main(String[] args) {
System.out.println(”Hello, world!”);
}
}[/java]

So how does one get started with Groovy? In this tutorial we will cover installing Groovy and creating a basic Groovy script. First off, you need to have a Java Virtual Machine installed. If you are running an operating system such as Mac OS X or any variety of Linux or Unix, chances are that you already have a JVM installed. If you are running Windows or if you do not have it installed, you should visit http://java.sun.com/javase/downloads/index.jsp and download a JDK for your platform. Once installed, you will have to set up an environment variable called JAVA_HOME that points to the path of your JDK. (That is beyond the scope of this introduction, but if you need help, search Google or post it in the comments!)

Once Java is installed and the JAVA_HOME variable is set up, then you need to install Groovy. Follow the installation guide on the Groovy website to download and configure it.

Groovy can be run a couple of different ways. You can use an interactive shell (groovysh), where you can enter a number of statements line by line. When you are ready to execut the statements, use the “execute” command to run your code. There is also an interactive Swing console (groovyConsole) which gives you a window user interface to run your Groovy code. To run more like a scripting language, you can type “groovy scriptname.groovy” to run a script from the command line. Finally, you can use the “groovyc” command to compile your Groovy script to Java bytecode that can be executed via the “java” command.

For your first Groovy script, open a text editor and save this file as ExampleOne.groovy:

[groovy]colors = ["red", "orange", "yellow", "green", "blue"]
println “The color list is: ” + colors.join(” “)
sortedColors = colors.sort()
println “The Sorted color list is: ” + sortedColors.join(” “)
[/groovy]

Let’s take a look at what this script should do, line by line:

[groovy]colors = ["red", "orange", "yellow", "green", "blue"][/groovy]

This sets up a list named colors, much like defining a new List in Java. In fact, lists in Groovy are instances of java.util.ArrayList and you can use all the methods from that class (as well as some additional ones like we will see below).

[groovy]println “The color list is: ” + colors.join(” “)[/groovy]

This line does two things: First off it takes all the elements of the colors list and appends them into a single string seperated by a space. Then it concatenates it to our message and prints it out on the screen.

[groovy]sortedColors = colors.sort()[/groovy]

This line creates a new list named sortedColors and its values are the sorted elements of the colors list. The final line is just like the line above where it prints out the list for us. If you run the script by typing in “groovy ExampleOne.groovy” on the command line, your output should look like this:

tim@slaggle.com [~]# groovy FirstExample.groovy
The color list is: red orange yellow green blue
The Sorted color list is: blue green orange red yellow

That’s it for this brief introduction to the Groovy language. In Part 2 we will cover the basic data types and looping constructs of Groovy, and Part 3 will introduce you to closures.