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
新闻热点
疑难解答