3.5 闭包

 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()


posted @ 2023-02-23 13:38  CodeWhisperer001  阅读(49)  评论(0编辑  收藏  举报