闭包
闭包是一段匿名函数,由lambda表达式派生。
传统方式求解:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35package groovy //求1到某个特定的数N之间所有偶数的和 def sum(n) { total = 0 for (int i = 2; i <= n; i += 2) { total += i } total } println("sum of even numbers from 1 to 10 is ${sum(10)}") //求1到某个特定的数N之间所有偶数的积 def product(n) { prod = 1 for (int i = 2; i <= n; i += 2) { prod *= i } prod } println("sum of even numbers from 1 to 10 is ${product(10)}") //求1到某个特定的数N之间所有偶数的平方所组成的集合 def sqr(n) { squared = [] for (int i = 2; i <= n; i += 2) { squared << i**2 } squared } println("sum of even numbers from 1 to 10 is ${sqr(10)}")
在groovy中,可以有更简洁的写法:
复制代码
1
2
3
4
5
6
7
8
9def pickEven(n, block) { for (int i = 2; i <= n; i += 2) { block(i) } } pickEven(10, { println(it) })
也可以写成这种形式:
复制代码
1
2pickEven(10){println(it)}
或者:
复制代码
1
2pickEven(10){evenNumber ->println(evenNumber)}
都可以。
像之前的求和,求积,可以写成完整的表达式:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16//求1到某个特定的数N之间所有偶数的和 total = 0 pickEven(10) { total += it } println("sum of even numbers from 1 to 10 is ${total}") //求1到某个特定的数N之间所有偶数的积 total = 1 pickEven(10) { total *= it } println("sum of even numbers from 1 to 10 is ${total}") //求1到某个特定的数N之间所有偶数的平方所组成的集合 total = [] pickEven(10) { total << it**2 } println("sum of even numbers from 1 to 10 is ${total}")
闭包的使用方式
上面的 例子介绍了如何在定义方法调用参数时即时创建闭包,此外,还可以将闭包复制给变量并复用,
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23package groovy def totalSelectValues(n, clouse) { total = 0 for (i in 1..n) { if (clouse(i)) { total += i println(total) } } total } println("total of even numbers from 1 to 10 is") println(totalSelectValues(10) { it % 2 == 0 }) def isOdd = { it % 2 != 0 } println("total of odd numbers from 1 to 10 is") println(totalSelectValues(10,isOdd))
在这个例子中,实现了将闭包作为参数传递,并且在构造器中的闭包进行解析,和直接创建的闭包不同,这种预创建的闭包可以多次调用,实现 了策略模式。
最后
以上就是谨慎大树最近收集整理的关于groovy学习历程(第四章:闭包)的全部内容,更多相关groovy学习历程(第四章内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复