//通过方法引用获取闭包
Closure smallerSix = six.&filter
this
:enclosing class where the closure is defined
owner
:enclosing class or enclosing closure where the closure is defined
delegate
: default toowner
12345678910 class Person {String namedef pretty = { "My name is $name" }}def p = new Person(name: 'Sarah')def t = new Thing(name: 'Teapot')p.pretty.resolveStrategy = Closure.DELEGATE_FIRST; //default OWNER_FIRSTp.pretty.delegate = tassert p.toString() == 'My name is Teapot'
闭包的两种使用方式
1 2 3 4 |
def adder = { x, y -> return x+y } assert adder(4, 3) == 7 assert adder.call(2, 6) == 8 |
1 2 3 4 5 6 |
//如果参数是闭包,可以将其放在括号后 //int.times应该是groovy的扩展方法 def benchmark(int repeat, Closure worker) { repeat.times { worker(it) } } |
curry从左向右固定参数,成为另一个闭包
1 2 3 4 |
def adder = { x, y -> return x+y } def addOne = adder.curry(1) assert addOne(5) == 6 |
range
1 2 3 4 5 |
def range = left..<right; range.contains 4; //previous next 用于++ 操作符, //实现Comparable 接口实现<=>操作符 |
*将将集合中元素插入到另一个集合
1 2 3 4 5 6 |
//list * spread operator List myList = [1, 2, 3] List flat = [0, *myList, 4] //*myList 表示将元素插入flat ,而不是mylist本身 //getAt,putAt 用于支持下标操作 |
map
1 2 3 4 5 6 7 |
//map def myMap = [a:1, b:2, c:3] def emptyMap = [:] def composed = [x:'y', *:myMap] //retrieve myMap.a myMap['a'] myMap.get('a') |
simple datatypes
1 2 3 4 5 6 7 |
1.23 //default bigDecimal [1, 2, 3].collect { it * 2 } //safe navigation operator if(company.getContact()?.getAddress()?.getCountry() == Country.NEW_ZEALAND) { ... } //default value def name = client.getName() ?: "" |
Posted in: IT人生
Comments are closed.