How Do You Invoke a Function in Groovy?

Problem scenario
You want to call a function and have it return a value. How do you do this?

(If you need assistance installing Groovy, see this posting for CentOS. or see this posting for Debian/Ubuntu Linux.)

Groovy has something called "Closures." These act like functions in other programming languages. The syntax looks like his with the square brackets portion being a comma-delimited list of parameters:

{ [closureParameters -> ] statements }

In the above, the "statements" signifies zero or more Groovy expressions. Here is an example of a Groovy statement:

println "${str1} ${param}"

The above will print the value of "str1" and the value of "param". Normally "param" will be a parameter passed at the time the closure is invoked. Closures can be invoked with syntax like this:"coolvalue")

The above would pass "coolvalue" as a parameter when nameOfClosure was invoked.

Create a Groovy program called test.groovy with the following code:

def str1 = "Cool attempt: ";
def contint = { param -> println "${str1} ${param}" }"This shows how a Closure is invoked!");

Leave a comment

Your email address will not be published. Required fields are marked *