天天看點

Groovy的展開操作符(Spread Operator)*.和*

Groovy的spread-dot操作符

  "*."操作符稱之為:spread-dot操作,即“展開(點)”操作。比如

list*.member

list.collect{ item -> item?.member } 

是等效的。此處member可以是屬性,也可以是get/set方法,甚至是一般的方法。如下例

  1. class SpreadDotDemo { 
  1.    def count 
  2. }
  3. def list = [new SpreadDotDemo(count:1),new SpreadDotDemo(count:2),new SpreadDotDemo(count:5) ] 
  1. assert 8==list*.count.sum() 
  2. assert 8==list.count.sum()//去掉*也可以的

“*.”也是安全解引用操作符(Safe Dereference Operator也稱為提領運算符),用以避免NullPointerException。

  1. def SpreadDotDemo demo
  2. demo.count //将抛空指針異常
  3. demo*.count //避免了null的檢查,并傳回null

跟spead doc操作符相關的事spead操作(*),它可以看作是逗号分隔的list的下标操作符的逆操作

  1. def getList(){ 
  1. return [1,2,3] 
  1. }
  2. def sum(a,b,c){ 
  1. return a + b + c 
  1. }
  1. assert 6 == sum(*list) 

看到了吧,示例中将list又展開為三個單獨的元素

源文檔 <http://agile-boy.iteye.com/blog/161057>

繼續閱讀