3.5 闭包

本文介绍了Groovy中的闭包概念,包括如何定义、调用闭包,以及如何传递参数和返回值。此外,还展示了闭包在遍历(如`upto`、`downto`、`times`方法)和处理字符串场景中的应用,如查找、过滤、转换等操作。
摘要由CSDN通过智能技术生成

3.5.1 闭包的基本技能点

闭包的定义:

闭包就是一段代码块,用{}括起来:

def c = { println 'hi groovy'}

**闭包调用/执行:

c.call()
c() //类似调用方法一样

闭包传入参数:**

无参数

// -> 前:闭包参数   -> 后:闭包体
def c = { -> println 'hi groovy'}
c.call()

可以传入一个参数

def c = { String str -> println "hi ${str}"}
c.call('groovy')

可以传入多个参数:(用逗号隔开参数即可)

def c = { String str,int num -> println "hi ${str} , hi ${num}"}
def num = 19
c.call('groovy',num)

有默认的参数:

所有闭包都有一个默认参数,不需要你显式声明,用it接收

def c = { println "hi ${it} "}
c.call('groovy')

如果你不想叫it,那么就需要自己手动显式将参数定义即可,一旦定义那么就没有默认参数了(隐式参数)

闭包返回值:

闭包一定有返回值,如果不写,就相当于返回null

def c = { println "hi ${it} "}
def result = c.call('groovy')
println result

可以定义返回值:

```
def c = { return "hi ${it} "}
def result = c.call('groovy')
println result
```

3.5.2 闭包的常见使用场景

1、与基本数据类型结合使用(for循环场景)

(1)案例:从2-7进行遍历: -------**upto

2.upto(7){println it}

底层对应源码:

(2)案例:1+2+3+。。。。+100 -------**upto

```
//1+2+3+。。。。+100
def result = 0
1.upto(100){result += it}
println result
```

(3)案例:输出7-2 -------**downto

7.downto(2){println it}

(4)案例:输出100以内的数 --- times (从0开始遍历到指定数结束)

3.times {println it}

(5)案例:1+2+。。。100 ----- times

def r = 0
101.times {r += it}
println r

补充:写法两种:

//如果闭包是调用方法的最后一个参数,可以直接将闭包写在外面
2.upto(7){println it} //常用
2.upto(7,{println it}) //不常用

**2、与字符串结合使用

package com.msb.test01

def s = "hi groovy 2023"

//遍历:PS :如果闭包是方法的最后一个参数,我们可以写在外面,不用非要写到()中
println s.each {println it} //each的返回值就是字符串s本身

//找到符合条件的第一个值
println s.find {it.isNumber()}
//PS :参照源码发现 !bcw.call(new Object[]{value} --》闭包返回值必须是布尔值

//找到符合条件的全部值
def list = s.findAll {it.isNumber()}
println list.toListString()

//判断任意一位是否满足条件
println s.any {it.isNumber()}

//判断每一位是否满足条件
println s.every {it.isNumber()}

//收集结果:
def list2 = s.collect {it.toUpperCase()}
println list2.toListString()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值