DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
Building Scalable Real-Time Apps with AstraDB and Vaadin
Register Now

Trending

  • Using OpenAI Embeddings Search With SingleStoreDB
  • Database Integration Tests With Spring Boot and Testcontainers
  • Essential Architecture Framework: In the World of Overengineering, Being Essential Is the Answer
  • What Is Envoy Proxy?

Trending

  • Using OpenAI Embeddings Search With SingleStoreDB
  • Database Integration Tests With Spring Boot and Testcontainers
  • Essential Architecture Framework: In the World of Overengineering, Being Essential Is the Answer
  • What Is Envoy Proxy?
  1. DZone
  2. Coding
  3. Languages
  4. Closures in Groovy

Closures in Groovy

Alex Staveley user avatar by
Alex Staveley
·
Jan. 13, 14 · Interview
Like (1)
Save
Tweet
Share
32.92K Views

Join the DZone community and get the full member experience.

Join For Free
The simpliest explanation of a closure in Groovy is that it is anonymous function. 
?
def closure = { println "I am a closure" }
closure() // Prints I am a closure
Ok, so first point here is that I am a closure is not printed when the closure is defined but only when it is invoked. Closures facilitate delayed execution. It is also possible to pass parameters to a closure 
?
def closureWithParameters = {x, y -> print(x  + " and " + y)}
closureWithParameters("Hello dudes", "Hello Mega Dude")  // Prints Hello dudes and Hello Mega Dude
When the closure has only one parameter, we don't even need the -> we can just use the implicit it variable. 
?
def closureWithParameters = { println it }
closureWithParameter("Hello dude")  // Prints Hello dude
Now, now, now kiddies. Closures don't just exist in Groovy, they exist in many languages and one of their features that people sometimes forget about is that they contain a representation of the function's lexical environment. In English, this means they get a snapshot of the context in which they are defined and only they they can access this snapshot and change it. In JavaScript, we can do something like this: 
?
function outerFuntion () {
var counter = 1;
function innerFunction() {
alert("Counter=" + counter++);
} 
return innerFunction;
}
Even though counter is defined in outerFunction() as a local variable, it is considered to be in innerFunction()'s lexical environment hence it can access it. When innerFunction() is returned as a closure it will get its own value of it that only it can access. So if we were to do this: 
?
var myClosure = outerFuntion();  // myFunc is now a pointer to the innerFunction closure.
myClosure();  // Executes Counter=1;
First, outerFunction() is executed and it returns the innerFunction closure. The variable is assigned to this closure. Now, now, now, note the key word here is "returned". innerFunction() is returned, it is not executed. So again we see the delay of execution characteristic of closures. Everytime we then execute the closure, the counter is increased. 
?
myClosure();  // Executes Counter=2;
myClosure();  // Executes Counter=3;
myClosure();  // Executes Counter=4;
myClosure();  // Executes Counter=5;
myClosure();  // Executes Counter=6;
So the closure has state, that it remembers across invocations. That state begins as the snapshot of the context in which the function is defined and it is something that only they closure can change. So yeah that's the key point of closures. They are a special kind of object that combines two things: a function, and the environment in which that function was created. The environment consists of variables that were in-scope at the time that the closure was created. Ok, so back onto Groovy. The same example would look like: 
?
def outerFunction () {
def counter = 1;
return {
print "Counter=" + counter++
}
}
?
def myClosure = outerFunction()
myClosure();  // executes 1
myClosure();  // executes 2
myClosure();  // executes 3
myClosure();  // executes 4
myClosure();  // executes 5
myClosure();  // executes 6
It's very similar to the JavaScript example. The word def is used instead of function. We just also make use of the fact you don't have to use the word function in Groovy when you want define an anonymous function. If we wanted to make the inner function anonymous in the JavaScript version we could do:
?
function outerFuntion () {
var counter = 1;
return function () {
alert("Counter=" + counter++);
};
}
var myClosure = outerFuntion();  // myFunc is now a pointer to the innerFunction closure.
myClosure();  // Executes Counter=1;
myClosure();  // Executes Counter=2;
But still have to use the word function, we just don't have to give it a name. Ok, so until the next time take care of yourselves
Groovy (programming language)

Published at DZone with permission of Alex Staveley, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Trending

  • Using OpenAI Embeddings Search With SingleStoreDB
  • Database Integration Tests With Spring Boot and Testcontainers
  • Essential Architecture Framework: In the World of Overengineering, Being Essential Is the Answer
  • What Is Envoy Proxy?

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com

Let's be friends: