首页 > 学院 > 开发设计 > 正文

Groovy闭包应用

2019-11-08 19:31:33
字体:
来源:转载
供稿:网友

Groovy闭包应用

1、闭包是Groovy的特性之一,类似于java中的匿名内部类,但功能更加强大。
def filter(array, block) {    for (val in array) {        block(val)    }}iarray = [1, 2, 3, 4, 5, 6, 7, 8, 9]total = []filter(iarray, { if (it % 2 == 0) total << it })PRintln total // [2, 4, 6, 8]total = []filter(iarray, { if (it > 5) total << it })println total // [6, 7, 8, 9]2、当闭包作为最后一个参数时,可以有其它写法
filter(iarray) { if (it % 2 == 0) total << it }3、闭包也可以作为属性,可以判断是否提供。
class Person {	def block	def setBlock(b) {		block = b;	}	def doSomeThing() {		if (block) {			block()		} else {			println "no block provide"		}			}}def p1 = new Person()p1.doSomeThing()def block = { println "block1" }def p2 = new Person()p2.setBlock(block)p2.doSomeThing()返回no block provideblock1
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表