Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1

Introduction to DSLs and Groovy


[ 14 ]

This produces the following output:


[fileUnder: Software Development, title: Groovy for DSL, author: Fergal
Dearle]


Groovy for DSL


Groovy for DSL


Closures


Closures are one of the most powerful language features in Groovy. Closures are
anonymous code fragments that can be assigned to a variable. Closures can be
invoked by the call method as follows:


def biggest = { number1, number2 ->
number1<number2?number2:number1
}
// We can invoke the call method of the Closure class
def result = biggest.call(7, 1)
println result
// We can use the closure reference as if it were a method
result = biggest(3, 5)
println result
// And with optional parenthesis
result = biggest 13, 1
println result

Closures can contain multiple statements and can therefore be as complex as you
like. In the following example, we iterate through a list looking for the biggest
number, and return it when we are done:


def listBiggest = { list ->
def biggest = list[0]
for( i in list)
if( i > biggest)
biggest = i
return biggest
}
def numberList = [ 8, 6, 7, 5, 3, 9]
println listBiggest( numberList)

http://www.ebook3000.com
Free download pdf