Groovy的spread-dot操作符
"*."操作符稱之為:spread-dot操作,即“展開(點)”操作。比如
list*.member
跟
list.collect{ item -> item?.member }
是等效的。此處member可以是屬性,也可以是get/set方法,甚至是一般的方法。如下例
- class SpreadDotDemo {
- def count
- }
- def list = [new SpreadDotDemo(count:1),new SpreadDotDemo(count:2),new SpreadDotDemo(count:5) ]
- assert 8==list*.count.sum()
- assert 8==list.count.sum()//去掉*也可以的
“*.”也是安全解引用操作符(Safe Dereference Operator也稱為提領運算符),用以避免NullPointerException。
- def SpreadDotDemo demo
- demo.count //将抛空指針異常
- demo*.count //避免了null的檢查,并傳回null
跟spead doc操作符相關的事spead操作(*),它可以看作是逗号分隔的list的下标操作符的逆操作
- def getList(){
- return [1,2,3]
- }
- def sum(a,b,c){
- return a + b + c
- }
- assert 6 == sum(*list)
看到了吧,示例中将list又展開為三個單獨的元素
源文檔 <http://agile-boy.iteye.com/blog/161057>