Closures in Groovy
Join the DZone community and get the full member experience.
Join For FreeThe 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
def closureWithParameters = {x, y -> print(x + " and " + y)} closureWithParameters("Hello dudes", "Hello Mega Dude") // Prints Hello dudes and Hello Mega Dude
def closureWithParameters = { println it } closureWithParameter("Hello dude") // Prints Hello dude
function outerFuntion () { var counter = 1; function innerFunction() { alert("Counter=" + counter++); } return innerFunction; }
var myClosure = outerFuntion(); // myFunc is now a pointer to the innerFunction closure. myClosure(); // Executes Counter=1;
myClosure(); // Executes Counter=2; myClosure(); // Executes Counter=3; myClosure(); // Executes Counter=4; myClosure(); // Executes Counter=5; myClosure(); // Executes Counter=6;
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
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;
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