Getting Groovy, Part II

Written By: James Williams

- 28 Jul 2006 -

Description: This tutorial introduces you to Groovy, a dynamically-typed scripting language for the Java Virtual Machine. Part II introduces for loops, switch-case, collections, and closures.

  1. For-Loop and Switch
  2. Collections
  3. Closures

Intro

In the previous article, we finished with running simple functions. Let's get more groovy...

As we just saw, if-else functions just like a Java if-else statement. While loops also are a direct transplant. Do...while doesn't work at all in Groovy and the for loop has a slightly different syntax.

For-loop

Groovy's for-loop seems to be more in line with the for-each loop from Java 1.5

public class ForExample { 
        public static void main(args) {
                for(arg in args)
                        println arg
        }
}

Specifying the type of the interval variable is not needed.

Switch-case

In Java, the cases for a switch-case can only be Strings, integers, or enumerations. Groovy will take anything including classes.

b = ["Word",42] 
for (i in b) { 
        switch (i) {
                case String.class:
                        println "I am a String"
                        break
                case Integer.class:
                        println "I am an Integer"
                        break
                default:
                break
        }
}

Don't worry about the b-assignment line for now. We'll talk about that next. As we can see, the switch checks the class type of the variable and acts accordingly. This feature allows use to write more concise expressive code without 50 million if-statements.

Next >>