0Pricing
Groovy & Gradle: JVM Automation and Build Engineering · 课时

理解 Groovy 闭包

学习闭包的概念、定义方式,以及它们在 Groovy 中的多种应用。

理解 Groovy 闭包 是 CoddyKit 上的免费 Groovy & Gradle: JVM Automation and Build Engineering 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Groovy & Gradle: JVM Automation and Build Engineering 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Groovy & Gradle: JVM Automation and Build Engineering 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

What Are Groovy Closures?

Welcome to the world of Groovy closures! A closure is essentially a block of code that can be treated like a variable.

Think of it as a mini-function you can define, store, and pass around. Closures are a powerful feature that make Groovy code very flexible and concise.

  • They are first-class citizens, meaning they can be assigned to variables, passed as arguments, and returned from methods.
  • They can capture variables from their surrounding scope, even after that scope has finished executing.

Basic Closure Syntax

Defining a closure is straightforward. You enclose your code block within curly braces {}. Let's see a simple example:

class Main {
  static void main(String[] args) {
    // Define a simple closure
    def sayHello = {
      println "Hello from a closure!"
    }

    // Call (execute) the closure
    sayHello()
  }
}

Closures with Parameters

Just like methods, closures can accept parameters. You list the parameters before the -> (arrow) operator, followed by the closure's body.

This allows your closure to perform operations based on the input it receives.

class Main {
  static void main(String[] args) {
    // Closure that takes two parameters
    def add = { num1, num2 ->
      return num1 + num2
    }

    // Call the closure with arguments
    def result = add(10, 5)
    println "Sum: ${result}"

    // You can also omit 'return' for the last statement
    def multiply = { a, b -> a * b }
    println "Product: ${multiply(4, 3)}"
  }
}

The 'it' Keyword

When a closure takes exactly one parameter, Groovy provides a special implicit variable called it. You don't need to declare it explicitly.

This makes single-parameter closures even more concise and readable, especially when used with collection methods.

class Main {
  static void main(String[] args) {
    // Closure using 'it' for a single parameter
    def square = { it * it }

    println "Square of 7: ${square(7)}"

    def greetPerson = { "Hello, ${it}!" }
    println greetPerson("Alice")
  }
}

Closures as Method Arguments

One of the most common and powerful uses of closures in Groovy is passing them as arguments to methods. Many Groovy methods, especially those on collections, are designed to accept closures.

If a closure is the last argument to a method, you can place it outside the parentheses, making the code look very clean and DSL-like.

class Main {
  static void main(String[] args) {
    def numbers = [1, 2, 3, 4, 5]

    // Using 'each' with a closure to iterate
    numbers.each { num ->
      println "Number: ${num}"
    }

    println "---"

    // Using 'collect' with a closure to transform
    def doubledNumbers = numbers.collect { it * 2 }
    println "Doubled: ${doubledNumbers}"
  }
}

Capturing Variables: Lexical Scope

Closures have lexical scope, meaning they remember and can access variables from the scope where they were defined, even if that scope no longer exists.

This is a key characteristic that differentiates closures from regular methods and allows them to carry context with them.

class Main {
  static void main(String[] args) {
    def name = "Groovy User" // Variable in the outer scope

    def introduce = {
      // The closure 'introduce' captures 'name'
      println "My name is ${name}."
    }

    introduce() // Calls the closure, accessing 'name'

    name = "CoddyKit Enthusiast" // Change the outer variable
    introduce() // The closure still references the updated 'name'
  }
}

Modifying Captured Variables

Not only can closures access captured variables, but they can also modify them. This creates a powerful way for closures to interact with their surrounding environment.

Be mindful when modifying external variables from within closures, as it can sometimes lead to less predictable code if not managed carefully.

class Main {
  static void main(String[] args) {
    def counter = 0 // A variable to be captured

    def increment = {
      counter++ // Closure modifies the outer 'counter'
      println "Counter is now: ${counter}"
    }

    increment() // Counter: 1
    increment() // Counter: 2
    increment() // Counter: 3

    println "Final counter value: ${counter}"
  }
}

Closure 'call()' Method

While you can execute a closure by simply using parentheses (e.g., myClosure()), closures are actually instances of the groovy.lang.Closure class.

This means they also have a call() method. Using call() is equivalent to direct execution and can sometimes be useful for clarity or when dynamically invoking closures.

class Main {
  static void main(String[] args) {
    def greet = { name ->
      println "Hello, ${name}!"
    }

    // Direct execution
    greet("World")

    // Execution using the call() method
    greet.call("Groovy")

    def add = { a, b -> a + b }
    println add.call(5, 7)
  }
}

Practical Use: Filtering Lists

Let's put closures to work with a practical example: filtering elements from a list. Groovy's collection methods, like findAll, are perfect for this.

You provide a closure that defines the condition for inclusion, and findAll returns a new list containing only the elements that satisfy that condition.

class Main {
  static void main(String[] args) {
    def numbers = [10, 25, 12, 30, 5, 45, 20]

    // Find numbers greater than 20
    def largeNumbers = numbers.findAll { it > 20 }
    println "Numbers > 20: ${largeNumbers}"

    // Find even numbers
    def evenNumbers = numbers.findAll { it % 2 == 0 }
    println "Even numbers: ${evenNumbers}"
  }
}

Closure Concepts Check

Which of the following statements about Groovy Closures are TRUE?

Recap: Understanding Closures

Great job! You've taken a significant step in understanding Groovy's powerful closures.

Here's a quick summary of what we covered:

  • Closures are code blocks treated as first-class citizens.
  • They use {} for definition and -> for parameters.
  • The it keyword simplifies single-parameter closures.
  • Closures are often passed as method arguments, enhancing Groovy's expressiveness.
  • They possess lexical scope, capturing and even modifying variables from their surrounding context.

In the next lesson, we'll explore how to apply closures to functional programming patterns in Groovy!

常见问题解答

「理解 Groovy 闭包」课时是免费的吗?

是的 — 「理解 Groovy 闭包」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Groovy & Gradle: JVM Automation and Build Engineering 课程的其余内容,请升级到 CoddyKit PRO。 Groovy & Gradle: JVM Automation and Build Engineering 课程共包含 4 节课。

「理解 Groovy 闭包」这节课中我会学到什么?

学习闭包的概念、定义方式,以及它们在 Groovy 中的多种应用。 你通过在浏览器中直接运行的动手代码来练习 Groovy & Gradle: JVM Automation and Build Engineering,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Groovy & Gradle: JVM Automation and Build Engineering 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Groovy & Gradle: JVM Automation and Build Engineering 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。

「理解 Groovy 闭包」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Groovy & Gradle: JVM Automation and Build Engineering 课中编写并运行代码吗?

能。每节 Groovy & Gradle: JVM Automation and Build Engineering 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. Groovy 集合增强功能
  2. 理解 Groovy 闭包
  3. 使用 Groovy 实现函数式模式
  4. 闭包的柯里化与组合
← 返回 Groovy & Gradle: JVM Automation and Build Engineering