groovy 闭包(Closure)

在 Groovy 中,闭包(Closure)是一个非常强大的特性。闭包是代码块,可以作为对象传递执行
它们不仅可以包含逻辑,还可以访问和修改其定义作用域中的变量。

闭包的基本语法

基本定义

{ [参数列表] -> 代码块 }
示例
// 无参数的闭包
def noParams = { println "Hello, Groovy!" }
noParams()  // 调用闭包

// 带参数的闭包
def withParams = { name -> println "Hello, $name!" }
withParams("Alice")

// 多参数的闭包
def multiParams = { first, last -> println "Hello, $first $last!" }
multiParams("Alice", "Smith")

引用一个方法作为闭包

def doubleMethod2(entry){
   //do sth
}
doubler2 = this.&doubleMethod2

闭包的基本使用

作为方法参数

作为方法参数—定义
// 使用默认参数类型({})
def benchmarkDefault(repeat, worker = {}) {
    for (int i = 0; i < repeat; i++) {
        worker.call(i)
    }
}

// 显式声明 Closure 类型
def benchmarkExplicit(repeat, Closure worker) {
    for (int i = 0; i < repeat; i++) {
        worker.call(i)
    }
}

//方法
作为方法参数-调用

闭包可以作为参数传递给方法,这使得 Groovy 非常适合用于 DSL(领域特定语言)和流畅的 API 设计。

def greet(Closure closure) {
    closure("World") // 隐式调用
 //   closure.call("World") // 显示调用
}

greet({ println "Hello, $it!" })
greet(){println "Hello, $it!" }
greet{println "Hello, $it!" } // 常用方法
作为方法参数-归纳
  1. a {}:最简洁的闭包调用方式,常用于配置脚本和 DSL。
  2. a.call {}:显式调用 call 方法,传递一个新的闭包。
  3. a.call({}):显式调用 call 方法,将闭包括在括号中传递,语法稍冗长。
  4. a.call() {}:结合方法调用和闭包传递,功能上与 a.call {} 相同,但语法更复杂。

实例&区别

// 定义一个方法 a,接受一个闭包作为最后一个参数
def a(Closure closure) {
    closure.call()
}

// 1. 直接调用 a 并传递闭包
a {
    println "Hello from a {}"
}

// 2. 调用 a 的 call 方法并传递闭包
a.call {
    println "Hello from a.call {}"
}

// 3. 调用 a 的 call 方法,传递闭包作为参数
a.call({
    println "Hello from a.call({})"
})

// 4. 调用 a 的 call 方法,传递闭包作为参数,使用空括号
a.call() {
    println "Hello from a.call() {}"
}

闭包的参数

闭包的默认参数

如果闭包没有指定参数,Groovy 会使用默认参数 it

def greet = { println "Hello, $it!" }
greet("World")

闭包的参数数量

def callClosure(Closure closure) {
    closure.getParameterTypes().size()
}

assert callClosure { a ->  } == 1
assert callClosure { a, b ->  } == 2
assert  callClosure { a, b, c -> } == 3

闭包的返回值

def square = { int x -> x * 2 }
assert square(4) == 8

def add = { int x, int y -> return x + y }
assert add(3, 5) == 8

闭包的作用域

闭包可以访问定义它们的作用域中的变量。这使得闭包非常灵活和强大。

def outerVar = "I am outside!"

def closure = {
    println outerVar
}

closure()  // 输出: I am outside!

复杂一点的例子

class Mother {
    int field = 1
    int foo(){
        return 2
    }

    Closure birth(param) {
        def local = 3
        def closure = { caller ->
            // [this, field, foo(), local, param, caller, this.owner]
            [this, field, foo(), local, param, caller]
        }
        return closure
    }
}

Mother julia = new Mother()
closure = julia.birth(4)
context = closure(this)
println context[0].class.name  // Mother

assert context[1..4] == [1,2,3,4]

println context[5]  //scirpt name: helloworld@6e9c413e
assert context[5] instanceof Script


firstClosure = julia.birth(4)
secondClosure = julia.birth(4)
assert false == firstClosure.is(secondClosure)

Delegate

闭包有一个 delegate 属性,可以动态地改变闭包执行时的上下文。这在构建 DSL 时非常有用。

class Person {
    String name
    def sayHello() {
        println "Hello, my name is $name"
    }
}

def person = new Person(name: "Alice")

def closure = {
    sayHello()
}

// 默认情况下,闭包的 delegate 是它自己
closure.delegate = person // 若没有这一行, 则会抛出`groovy.lang.MissingMethodException`
closure.resolveStrategy = Closure.DELEGATE_FIRST
closure()  // 输出: Hello, my name is Alice

Resolve Strategy

resolveStrategy 决定了闭包如何解析未找到的属性和方法。常用的策略包括:

  • Closure.OWNER_FIRST: 优先从闭包的 owner 中查找方法和属性。
  • Closure.DELEGATE_FIRST: 优先从闭包的 delegate 中查找方法和属性。
  • Closure.OWNER_ONLY: 仅从闭包的 owner 中查找方法和属性。
  • Closure.DELEGATE_ONLY: 仅从闭包的 delegate 中查找方法和属性。
class Owner {
    def greet() {
        println "Hello from Owner!"
    }
}

class Delegate {
    def greet() {
        println "Hello from Delegate!"
    }
}

def owner = new Owner()
def delegate = new Delegate()

def closure = {
    greet()
}
closure() // 输出:Hello from Origin-clsss!

def greet() {
        println "Hello from Origin-clsss!"
}

closure() //输出: Hello from Origin-clsss!

closure.delegate = delegate
closure.owner = owner
closure.resolveStrategy = Closure.DELEGATE_FIRST
closure()  // 输出: Hello from Delegate!

closure.resolveStrategy = Closure.OWNER_FIRST
closure()  // 输出: Hello from Owner!

闭包的高级特性

curry

curry 的基本思想是一个多个参数的函数,传递较少的参数给函数来固定一些值.
一个典型的例子是选择一些数 n 并且传递给函数与后面传递的单个参数进行相加.

def adder = { a, b -> a + b }
def addOne = adder.curry(1)
assert addOne(5) == 6

复杂一点的例子
假设你需要实现一个日志记录器,

  • 它应该支持行数的过滤,
  • 日志的格式化,
  • 并且输出它们到一个设备上,
  • 每一个记录器都应该是可配置的,
//configuration use
def configurator = { format, filter, line -> 
    filter(line) ? format(line) : null
}

// formatting use
def appender = { config,append,line -> 
    def out = config(line)
    if (out) append(out)
}

def dateFormater = { line -> "${new Date()}: $line" }
def errorFilter =  { line -> line.contains('ERROR') }
def consonleAppender = { line -> println line }


def configurator1 = configurator.curry(dateFormater, errorFilter)
def log1 = appender.curry(configurator1, consonleAppender)

log1('ERROR: something went wrong')
log1('INFO: everything is fine')

通过 isCase 方法进行分类

assert [1,2,3].grep{ it<3 } == [1,2]
  • 5
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
【优质项目推荐】 1、项目代码均经过严格本地测试,运行OK,确保功能稳定后才上传平台。可放心下载并立即投入使用,若遇到任何使用问题,随时欢迎私信反馈与沟通,博主会第一时间回复。 2、项目适用于计算机相关专业(如计科、信息安全、数据科学、人工智能、通信、物联网、自动化、电子信息等)的在校学生、专业教师,或企业员工,小白入门等都适用。 3、该项目不仅具有很高的学习借鉴价值,对于初学者来说,也是入门进阶的绝佳选择;当然也可以直接用于 毕设、课设、期末大作业或项目初期立项演示等。 3、开放创新:如果您有一定基础,且热爱探索钻研,可以在此代码基础上二次开发,进行修改、扩展,创造出属于自己的独特应用。 欢迎下载使用优质资源!欢迎借鉴使用,并欢迎学习交流,共同探索编程的无穷魅力! 基于业务逻辑生成特征变量python实现源码+数据集+超详细注释.zip基于业务逻辑生成特征变量python实现源码+数据集+超详细注释.zip基于业务逻辑生成特征变量python实现源码+数据集+超详细注释.zip基于业务逻辑生成特征变量python实现源码+数据集+超详细注释.zip基于业务逻辑生成特征变量python实现源码+数据集+超详细注释.zip基于业务逻辑生成特征变量python实现源码+数据集+超详细注释.zip基于业务逻辑生成特征变量python实现源码+数据集+超详细注释.zip 基于业务逻辑生成特征变量python实现源码+数据集+超详细注释.zip 基于业务逻辑生成特征变量python实现源码+数据集+超详细注释.zip
提供的源码资源涵盖了安卓应用、小程序、Python应用和Java应用等多个领域,每个领域都包含了丰富的实例和项目。这些源码都是基于各自平台的最新技术和标准编写,确保了在对应环境下能够无缝运行。同时,源码中配备了详细的注释和文档,帮助用户快速理解代码结构和实现逻辑。 适用人群: 这些源码资源特别适合大学生群体。无论你是计算机相关专业的学生,还是对其他领域编程感兴趣的学生,这些资源都能为你提供宝贵的学习和实践机会。通过学习和运行这些源码,你可以掌握各平台开发的基础知识,提升编程能力和项目实战经验。 使用场景及目标: 在学习阶段,你可以利用这些源码资源进行课程实践、课外项目或毕业设计。通过分析和运行源码,你将深入了解各平台开发的技术细节和最佳实践,逐步培养起自己的项目开发和问题解决能力。此外,在求职或创业过程中,具备跨平台开发能力的大学生将更具竞争力。 其他说明: 为了确保源码资源的可运行性和易用性,特别注意了以下几点:首先,每份源码都提供了详细的运行环境和依赖说明,确保用户能够轻松搭建起开发环境;其次,源码中的注释和文档都非常完善,方便用户快速上手和理解代码;最后,我会定期更新这些源码资源,以适应各平台技术的最新发展和市场需求。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值