Groovy is often used for scripting, automation, and configuration, and closures are at the heart of that power. In this tutorial, you'll learn how to apply Groovy closures to solve practical scripting tasks, including file processing, task pipelines, and configuration handling.
By the end, you'll see how closures make Groovy a top choice for concise, flexible automation scripts.
Preparation
Make sure Groovy is installed. You can use:
- SDKMAN (Linux/macOS):
sdk install groovy
- Groovy Console for interactive editing:
groovyConsole
Online editors like TutorialsPoint Groovy Editor https://www.tutorialspoint.com/compilers/online-groovy-compiler.htm
Save code in ClosureScopeExample.groovy and run with groovy ClosureScopeExample.groovy.
Example 1: File Processing with Closures
Groovy makes reading files elegant with closure support.
Read a file line by line
new File('example.txt').eachLine { line, index ->
println "${index + 1}: $line"
}
Filter and process lines
def errors = []
new File('app.log').eachLine { line ->
if (line.contains('ERROR')) {
errors << line
}
}
println "Found ${errors.size()} errors"
Example 2: Task Pipelines
Define a sequence of tasks as closures and run them dynamically.
def tasks = [
{ println 'Step 1: Clean' },
{ println 'Step 2: Compile' },
{ println 'Step 3: Test' },
{ println 'Step 4: Package' }
]
tasks.each { it() }
Closures help model modular and reusable steps in a process.
Example 3: Directory Traversal
List all .groovy files in a directory recursively:
def listGroovyFiles = { dir ->
dir.eachFileRecurse { file ->
if (file.name.endsWith('.groovy')) {
println file.path
}
}
}
listGroovyFiles new File('.')
Example 4: Using Closures for Configuration
You can build a DSL-style configuration with closures.
class AppConfig {
String env
String db
def configure(Closure cl) {
cl.delegate = this
cl.resolveStrategy = Closure.DELEGATE_FIRST
cl()
}
}
def config = new AppConfig()
config.configure {
env = 'production'
db = 'postgres'
}
println "Environment: ${config.env}, DB: ${config.db}"
Example 5: Custom Build Scripts
Build a simple build script using closures and a mini DSL:
class BuildScript {
def steps = []
def step(String name, Closure action) {
steps << [name: name, action: action]
}
def run() {
steps.each {
println "Running: ${it.name}"
it.action()
}
}
}
def build = new BuildScript()
build.step('Compile') { println 'Compiling source...' }
build.step('Test') { println 'Running tests...' }
build.step('Deploy') { println 'Deploying app...' }
build.run()
Conclusion
Groovy closures aren't just a language feature — they're a practical tool for writing elegant and flexible scripts. Whether you're processing files, chaining tasks, or writing custom DSLs, closures let you write less code that does more.
With these real-world examples, you're ready to build powerful automation and scripting solutions in Groovy.
This wraps up our Groovy Closures tutorial series. Next, consider exploring Groovy's integration with Gradle, REST APIs, or Java interoperability for even more scripting and automation possibilities.
You can find the full source for this tutorial on our GitHub.
That just the basic. If you need more deep learning about Groovy and Grails you can take the following cheap course:
- Mastering Grails. A Comprehensive Grails Course.
- Groovy Scripting for Developers / Testers
- Introduction to JVM Languages Clojure, Kotlin, and Groovy
Thanks!