Programmer's Wiki

Groovy includes a lot of syntatic sugar that makes programming much easier than it is in java. However it can make things difficult to understand if you don't know what it is.

Method overloading[]

method overloading allows you to use a suitable operator instead of a method call. This makes you code simpler and more readable.

result << left[0]

in this case the left shift operator is overloaded for an append operation on a collection.

result += left

the list result has had another list concatenated to it.


Ranges are a type of collection that is defined with a start point and an end point. This means that you don't have to define every item in the collection.

  def num = [0..10]

all numbers from 0 to 10

  def num = [a..z]

the lowercase alphabet

Ranges can also be applied to a collection to create a slice. a subset of the collection.

  def slice = list[0..3]

will return a collection of the first three items in the collection.

Cast Operator[]

a hash can be converted to an object of another type using the "as" operator

def dog = ["name":"Fido", "speak":{println "woof"}] as Dog


By default map keys are Strings. to get around that you have to use round brackets

def key = "bob"

def m = [key:"value"]

println m
println m["key"] == null    //why is this false
println m["bob"] == null    //and this true

m = [(key):"value"] 

println m
println m["key"] == null    //thats better
println m["bob"] != null


see JavaBeans