Getting Groovy Without The Bad Clothes
Written By: James Williams
- 20 Jul 2006 -
Description: This tutorial introduces you to Groovy, a dynamically-typed scripting language for the Java Virtual Machine, and runs you through creating your first script.
Your First Program
Hello World in Groovy looks very similar to Hello World in Java:
public class HelloWorld { public static void main(String [] args) { System.out.println("Hello, World!"); } }
Ok, so it is exactly the same as Hello World in Java. The key point is that Groovy is similar enough to recognize about 95% of Java code. Why you would want to write all that in Groovy is beyond me but you can if you like. Groovy is all about writing more concise code, so lets do that. Groovy only requires parentheses when they are absolutely required(conditional statements and no parameter functions). Semicolons are also optional and only required when separating two or more statements on one line. Code can also run outside a class instance.[Technically it compiles the code and injects it into a class but for our purposes, we'll assume the former].
Our five line program, 80% of which was environment setup, is now:
System.out.println "Hello, World!"
The print functions have been specially registered so they can be called without the full classpath. Now we have:
println "Hello, World!"
Declarations
Variables and functions must have an access modifier, a type or def. For functions, def acts like public, in front of a variable name, it declares the variable at the default access level. These are NOT required for function parameters.
// These are fine def a int i public x
N-Factorial
When it comes to declaring functions, the use of parentheses is required. Here is the corresponding code for n-factorial. Though we can specify the return type, we can let Groovy determine the type at runtime.
public fact(a) { if (a>1) return a*fact(a-1) else return 1 }
We'll be revisiting n-factorial in the coming sections to make it more groovy...