Groovy Bar & Grill

December 9, 2008

ReverseEcho.groovy

Filed under: Groovy Grill — jawild59 @ 10:23 pm

There’s a great line from the movie, The Truman Show, that explains why Truman never questioned his life circumstances: “We accept the reality of the world with which we’re presented.” It’s the same with Java. We didn’t know how tedious it was until Groovy showed us a better way.
Just how tedious is Java. Let’s look at an example that prints out the reverse of the command line arguments (e.g. “This is a test” prints out as “tset a si sihT”)


public class ReverseEcho {
  public static void main(String[] args) {
    for (int i = args.length - 1; i >= 0; i--) {
      for (int j = args[i].length() 1; j >= 0; j--) {
        System.out.print(args[i].charAt(j));
      }
      System.out.print(" ");
    }
  }
}
  

When you don’t know any better, well, that’s what you have to do: set up nested for loops and traverse in reverse. You’re happy as a bit in a bucket until Groovy comes along and presents a new reality.


args.reverseEach {
  print "${it.reverse()} "
}

Yep, Groovy really makes it that easy. args is an implicitly defined list that contains the command line arguments. reverseEach() is a shortcut (a concept mostly absent in Java) for reverse().each() and iterates over each element in the list in reverse order. reverse() is also a GDK method on string and does exactly what you might think, it creates a new string which is the reverse of the original.

No Comments Yet »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment

Blog at WordPress.com.