programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
• Campbell Ritchie
• Jeanne Boyarsky
• Ron McLeod
• Paul Clapham
• Liutauras Vilda
Sheriffs:
• paul wheaton
• Rob Spoor
• Devaka Cooray
Saloon Keepers:
• Stephan van Hulst
• Tim Holloway
• Carey Brown
• Frits Walraven
• Tim Moores
Bartenders:
• Mikalai Zaikin

# Clousers in Groovy

Posts: 3479
• Number of slices to send:
Optional 'thank-you' note:
Hi.
1- def toTriple = {n -> n * 3}
what is -> ?
2- def f = { list, value -> list << value }
What is << value ?
3- c = { value1 -> def it = 789; [value1, it] }
Why there is semicolon after it delaration ?
Thanks for help.

Ranch Hand
Posts: 15304
6
• Number of slices to send:
Optional 'thank-you' note:
1- def toTriple = {n -> n * 3}
what is -> ?

From Groovy in Action:

Informally, a closure can be recognized as a list of statements within curly braces, like any other code block. It optionally has a list of identifiers in order to name the parameters passed to it, with an -> arrow marking the end of the list.

I've not really seen any examples like the one you have posted. This example makes the definition clearer:

And the result of this statement would be:
1
2
3

Each index of the list [1,2,3] becomes the value for entry over the iteration.

2- def f = { list, value -> list << value }
What is << value ?

In this situation the << appends the value to the list. So if you did this in the groovy console:

Your list would then become [1,2,3,4]

3- c = { value1 -> def it = 789; [value1, it] }
Why there is semicolon after it delaration ?

Because it's a declaration. If you left the semicolon off then groovy would think that [value1, it] was also part of it. I wouldn't expect to see this syntax much though.

You should pick up Groovy in Action. It's a great book.

Posts: 3479
• Number of slices to send:
Optional 'thank-you' note:
When to use the def keyword ?
What is the difference between method/variable declared with def and non-def method/variable ?

Gregg Bolinger
Ranch Hand
Posts: 15304
6
• Number of slices to send:
Optional 'thank-you' note:

Originally posted by John Todd:
When to use the def keyword ?
What is the difference between method/variable declared with def and non-def method/variable ?

John, this information is available on the Groovy website (http://groovy.codehaus.org/Blocks%2C+Closures%2C+and+Functions) and in Groovy in Action. Please don't mistake our helpfulness as compensation for you being lazy.