groovy学习历程(第四章:闭包)

闭包
闭包是一段匿名函数,由lambda表达式派生。

传统方式求解:

 	package 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中,可以有更简洁的写法:

def pickEven(n, block) {
    for (int i = 2; i <= n; i += 2) {
        block(i)
    }
}

pickEven(10, { println(it) })

也可以写成这种形式:

pickEven(10){println(it)}

或者:

pickEven(10){evenNumber ->println(evenNumber)}

都可以。
像之前的求和,求积,可以写成完整的表达式:

//求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}")

闭包的使用方式

上面的 例子介绍了如何在定义方法调用参数时即时创建闭包,此外,还可以将闭包复制给变量并复用,

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


在这个例子中,实现了将闭包作为参数传递,并且在构造器中的闭包进行解析,和直接创建的闭包不同,这种预创建的闭包可以多次调用,实现 了策略模式。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

离离原上草77

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值