Skip to end of metadata
Go to start of metadata

Up and Running

Quick Start

Getting started

Getting Started

Setting up your Java environment

Groovy requires Java, so you need to have a version available (while groovy 1.6 supported JDK 1.4 or greater, for groovy 1.7 onwards, minimum JDK 1.5 is needed). Here are the steps if you don't already have Java installed:

  • Get the suitable Java distribution from the http://java.sun.com website.
  • Run the installer.
  • Set the JAVA_HOME environment variables. On Windows, follow these steps:
    • Open the System control panel
    • Click the Advanced tab
    • Click the Environment Variables button
    • Add a new System variable with the name JAVA_HOME and the value of the directory Java was installed in (mine is C:\Program Files\Java\jdk1.5.0_04)
    • Optionally add %JAVA_HOME%\bin to your system path
      (Note: as an alternative to setting a system environment variable, you can create yourself a '.bat' or '.cmd' file which sets the variable. You then need to run that batch file in any console window in which you wish to run Java and double clicking on '.bat' or '.cmd' files containing Java invocation instructions won't work. If you are unsure about what this means, follow the earlier instructions.)

Setting up your Groovy environment

Download the Groovy installer or binaries from the downloads page and follow the installation instructions.  (There is currently an issue where you cannot have spaces in the path where Groovy is installed under windows.  So, instead of accepting the default installation path of "c:\Program Files\Groovy" you will want to change the path to something like "c:\Groovy")

OR

  • Get a copy of the Groovy distribution from the website, and copy it to some place on your hard drive.
  • Unzip the groovy archive to some logical place on your hard drive, I have mine in C:\dev\groovy-2.0.5
  • Set the GROOVY_HOME environment variables. On Windows, follow these steps:
    • Optionally add a new System variable with the name GROOVY_HOME and the value of the directory groovy was installed in (mine is C:\dev\groovy-2.0.5)
    • Start a command prompt, and type "set" and hit return to see that your environment variables were set correctly.
  • Optionally add %GROOVY_HOME%\bin to your system path
  • Try opening groovyConsole.bat by double clicking on the icon in the bin directory of the Groovy distribution. If it doesn't work, open a command prompt, and change to the bin directory and run it from there to see what the error message is. If it is complaining about not finding parts of Groovy, then setting GROOVY_HOME may help,

Setting up optional jar files

You may wish to obtain optional jar files, either corresponding to Groovy modules (see module documentation for details) or corresponding to other Java classes you wish to make use of from Groovy. Some possibilities are listed below:

Name

From

Description

jtds-version.jar

http://jtds.sourceforge.net

Database driver for SQL Server and/or Sybase

hsqldb-version.jar

http://www.hsqldb.org/

Database driver for HSQLDB, a 100% Java database

The recommended way for making Groovy be aware of your additional jar files is to place them in a predefined location. Your Groovy install should include a file called groovy-starter.conf. Within that file, make sure a line such as


is not commented out. The user.home system property is set by your operating system. (Mine is C:\Document and Settings\paul. Now simply place your jar files into the .groovy/lib directory.
(Note: as an alternative, you can set up a CLASSPATH variable and make sure it mentions all of your additional jar files, otherwise Groovy works fine with an empty or no CLASSPATH variable.)

Hello, World

In the top part of the window of the groovyConsole, type the following


And then type <CTRL-R>.
Notice that the text gets printed out in the OS console window (the black one behind the groovyConsole window) and the bottom part of the groovyConsole says:


The line starting with "groovy>" is just the text of what the console processed. The "null" is what the expression "evaluated to". Turns out the expression to print out a message doesn't have any "value" so the groovyConsole printed "null".
Next try something with an actual value. Replace the text in the console with:


or your favorite arithmetic expression, and then type <CTRL-R> (I'm going to stop telling you to hit <CTRL-R>, I think you get the idea). Now the "value" printed at the bottom of the groovyConsole has more meaning.

Variables

You can assign values to variables for later use. Try the following:

 

Lists and Maps

The Groovy language has built-in support for two important data types, lists and maps (Lists can be operated as arrays in Java language). Lists are used to store ordered collections of data. For example an integer list of your favorite integers might look like this:


You can access a given item in the list with square bracket notation (indexes start at 0):


Should result in this output:


You can get the length of the list with the "size" method:


Should print out:


But generally you shouldn't need the length, because unlike Java, the preferred method to loop over all the elements in an list is to use the "each" method, which is described below in the "Code as Data" section.
Another native data structure is called a map. A map is used to store "associative arrays" or "dictionaries". That is unordered collections of heterogeneous, named data. For example, let's say we wanted to store names with IQ scores we might have:


Note that each of the values stored in the map is of a different type. Brett's is an integer, Pete's is a string, and Andrew's is a floating point number. We can access the values in a map in two main ways:


Should produce the output:


To add data to a map, the syntax is similar to adding values to an list. For example, if Pete re-took the IQ test and got a 3, we might:


Then later when we get the value back out, it will be 3.


should print out 3.
Also as an aside, you can create an empty map or an empty list with the following:


To make sure the lists are empty, you can run the following lines:


Should print a size of 0 for the List and the Map.

Conditional Execution

One of the most important features of any programming language is the ability to execute different code under different conditions. The simplest way to do this is to use the '''if''' construct. For example:


Don't worry too much about the first line, it's just some code to determine whether it is currently before noon or after. The rest of the code executes as follows: first it evaluates the expression in the parentheses, then depending on whether the result is '''true''' or '''false''' it executes the first or the second code block. See the section below on boolean expressions.
Note that the "else" block is not required, but the "then" block is:

 

Boolean Expressions

There is a special data type in most programming languages that is used to represent truth values, '''true''' and '''false'''. The simplest boolean expression are simply those words. Boolean values can be stored in variables, just like any other data type:


A more complex boolean expression uses one of the boolean operators:


Most of those are probably pretty intuitive. The equality operator is '''==''' to distinguish from the assignment operator '''='''. The opposite of equality is the '''!=''' operator, that is "not equal"
So some examples:


Boolean expressions are especially useful when used in conjunction with the '''if''' construct. For example:


An especially useful test is to test whether a variable or expression is null (has no value). For example let's say we want to see whether a given key is in a map:


Generally null is used to indicate the lack of a value in some location.

Debugging and Troubleshooting Tips

  • Print out the class of a variable that you're interested in with myVar.getClass(). Then look up the documentation for that class.
  • If you're having trouble with a complex expression, pare it down to a simpler expression and evaluate that. Then build up to your more complex expression.
  • Try restarting the groovyConsole (this will clear out all the variables so you can start over.
  • Look for the topic you're interested in in the Groovy User Guide

If you are a Java developer

Code as data

Closures

One of the things that makes Groovy different than most compiled languages is that you can create functions that are first class objects. That is you can define a chunk of code and then pass it around as if it were a string or an integer. Check out the following code:

The curly braces around the expression "it * it" tells the Groovy compiler to treat this expression as code. In the software world, this is called a "closure". In this case, the designator "it" refers to whatever value is given to the function. Then this compiled function is assigned to the variable "square" much like those above. So now we can do something like this:

and get the value 81.

This is not very interesting until we find that we can pass this function "square" around as a value. There are some built in functions that take a function like this as an argument. One example is the "collect" method on arrays. Try this:

This expression says, create an array with the values 1,2,3 and 4, then call the "collect" method, passing in the closure we defined above. The collect method runs through each item in the array, calls the closure on the item, then puts the result in a new array, resulting in:

For more methods you can call with closures as arguments, see the Groovy GDK documentation.

By default closures take 1 parameter called "it", you can also create closures with named parameters. For example the method Map.each() can take a closure with two variables, to which it binds the key and associated value:

Produces:

More Closure Examples

Here are a few more closure examples. This first one shows a couple of things. First, the closure is interacting with a variable outside itself. That is, the closure's purpose is to put together the parts of a stock order held in the array orderParts, by adding (appending) it to the variable fullString. The variable fullString is not in the closure. The second thing that is different about this example is that the closure is "anonymous", meaning that it is not given a name, and is defined in the place where the each method is called.

You can probably guess what this prints out.

The next example is another anonymous closure, this time, summing up the values stored in a map.

Dealing with Files

Reading data from files is relatively simple. First create a text file, and call it myfile.txt. It doesn't matter what's in it, just type some random text into it and save it on your C: drive in the \temp directory. Then type the following code in the groovyConsole:

This should print out every line in the file prefixed with "File line: ". The first two lines of the code simply declare variables to specify where the file is located. The variable names don't have any special significance, and as you can see, all we do is combine them when we use them. Note that because the backslash character has special meaning in groovy, you have to use two of them to tell it that you '''really''' mean a backslash.

The next line that starts "myFile =" creates a new File object. An object is simply a collection of related methods and data. For example, a file object might have data describing its location, in this case "C:\temp\myfile.txt", and maybe a method to delete the file if it exists. In this case the only method we are going to use is the eachLine method, which we call in the last line of code. The line before that is a simple closure definition, that you have seen several times by this point.

Dealing with strings

Strings in Groovy have all the same functionality of Java strings. That is, a Groovy string is just a Java string with a few extra things added to it. Because of that, we can refer to the Java documentation for the String class to find out some of the interesting things we can do with it. For example, look in the section entitled '''Method Summary''' at the description for the '''split''' method. This method does something very useful, which is to split a string based on a regular expression. We will talk more about regular expressions later, but for now the only thing you have to know is that the simplest regular expression is a single character. So let's say that we want to split up the components of the date "2005-07-04", so that we can add one to the year to get the date of next fourth of July. We might:

This code brings together a bunch of things we have talked about before. There are two new things, first is the use of the split method on a String. Second is the call of toInteger() on a String. This call to toInteger simply tells Groovy that you want to treat that data as a number rather than a String. See what happens if you run the same code without ".toInteger()" at the end of the third line.

Another thing you might notice is that toInteger is not listed in the Java documentation for string. That is because it is one of the extra features that Groovy has added to Strings. You can also take a look at the documentation for the Groovy extensions to Java objects.

  • No labels