Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Groovy requires Java, so you need to have a version available (while groovy 1.6 supports 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 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-12.0-jsr-06.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-12.0-jsr-06.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,

...

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

Code Block
none
none

load ${user.home}/.groovy/lib/*

...

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

Code Block

println "Hello, World!"


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:

Code Block

groovy> println "Hello, World!"
null


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:

Code Block

123+45*67


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.

...

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

Code Block

x = 1
println x

x = new java.util.Date()
println x

x = -3.1499392
println x

x = false
println x

x = "Hi"
println x

 

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:

Code Block

myList = [1776, -1, 33, 99, 0, 928734928763]


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

Code Block

println myList[0]


Should result in this output:

Code Block

1776


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

Code Block

println myList.size()


Should print out:

Code Block

6


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:

Code Block

scores = [ "Brett":100, "Pete":"Did not finish", "Andrew":86.87934 ]


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:

Code Block

println scores["Pete"]
println scores.Pete


Should produce the output:

Code Block

Did not finish
Did not finish


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:

Code Block

scores["Pete"] = 3


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

Code Block

println scores["Pete"]


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

Code Block

emptyMap = [:]
emptyList = []


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

Code Block

println emptyMap.size()
println emptyList.size()

...

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:

Code Block

amPM = Calendar.getInstance().get(Calendar.AM_PM)
if (amPM == Calendar.AM)
{
	println("Good morning")
} else {
	println("Good evening")
}


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:

Code Block

amPM = Calendar.getInstance().get(Calendar.AM_PM)
if (amPM == Calendar.AM)
{
	println("Have another cup of coffee.")
}

 

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:

Code Block

myBooleanVariable = true


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

Code Block

* ==
* !=
* >
* >=
* <
* <=


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:

Code Block

titanicBoxOffice = 1234600000
titanicDirector = "James Cameron"

trueLiesBoxOffice = 219000000
trueLiesDirector = "James Cameron"

returnOfTheKingBoxOffice = 752200000
returnOfTheKingDirector = "Peter Jackson"

theTwoTowersBoxOffice = 581200000
theTwoTowersDirector = "PeterJackson"

titanicBoxOffice > returnOfTheKingBoxOffice  // evaluates to true
titanicBoxOffice >= returnOfTheKingBoxOffice // evaluates to true
titanicBoxOffice >= titanicBoxOffice         // evaluates to true
titanicBoxOffice > titanicBoxOffice          // evaluates to false
titanicBoxOffice + trueLiesBoxOffice < returnOfTheKingBoxOffice + theTwoTowersBoxOffice  // evaluates to false

titanicDirector > returnOfTheKingDirector    // evaluates to false, because "J" is before "P"
titanicDirector < returnOfTheKingDirector    // evaluates to true
titanicDirector >= "James Cameron"           // evaluates to true
titanicDirector == "James Cameron"           // evaluates to true


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

Code Block

if (titanicBoxOffice + trueLiesBoxOffice > returnOfTheKingBoxOffice + theTwoTowersBoxOffice)
{
	println(titanicDirector + " is a better director than " + returnOfTheKingDirector)
}


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:

Code Block

suvMap = ["Acura MDX":"\$36,700", "Ford Explorer":"\$26,845"]
if (suvMap["Hummer H3"] != null)
{
 	println("A Hummer H3 will set you back "+suvMap["Hummer H3"]);
}

...