Last editor: Dave Cherry, last modified: Aug 22, 2009
Firstly, groovy supports either single or double quotes as string delimiters. It also supports triple quote syntax that ends only when another triple quote is found.
Groovy allows expressions to be embedded into strings, by enclosing a groovy expression inside "${ <groovy expression> }". Here are a few examples:
String name = "Dave"
String formattedString = """
This string
has more than one line.
"""
int val = 234
println("Name: ${name}, val: ${val}")
println("Square of val = ${val * val}")
println("Square root of val = ${Math.sqrt(val)}")
Consider a closure as a block of anonymous code that can be stored as a variable and passed as a parameter. For example:
def myClosure = {value -> value * value}
println "${myClosure(4)}"
Groovy lists are first class objects from the collection framework, implementing java.util.List; as such they can be passed to and from Java code. Here are a few examples of declaring and accessing a list in groovy:
def emptylist = [ ]
def populatedList = [ 'a', 'b' ]
def nameList = ['dave', 'joe', 'fred']
nameList.each {
n ->
println "name is ${n}"
}
println "${nameList[0]}"
As with lists above, maps in groovy are implementations of java.util.Map and therefore can be used from anywhere.A map can be accessed in several ways as can be seen above, firstly we can use the [ ] operator, and we can also access map elements by key as if they were members of the class.
def addressByName = [ 'dave' : 'some address', 'joe' : 'another address']
println "${addressByName['dave']}"
println "${addressByName.joe}"