2014年5月5日 星期一

[ GroovyGN ] The Spread-Dot Operator

來源自 這裡 
Preface: 
Groovy adds some nice operators to the language to write brief code. We already learned about the Elvis operator and the Spaceship operator. And now we see what the spread-dot operator is about and what it does. The spread-dot operator (*.) is used to invoke a method on all members of a Collection object. The result of using the spread-dot operator is another Collection object. 

Sample Code: 
  1. class Language {  
  2.     String lang  
  3.     def speak() { "$lang speaks." }  
  4. }  
  5.   
  6. // Create a list with 3 objects. Each object has a lang   
  7. // property and a speak() method.   
  8. def list = [       
  9.     new Language(lang: 'Groovy'),       
  10.     new Language(lang: 'Java'),       
  11.     new Language(lang: 'Scala')   
  12. ]    
  13.   
  14. // Use the spread-dot operator to invoke the speak() method.   
  15. assert ['Groovy speaks.''Java speaks.''Scala speaks.'] == list*.speak()   
  16. assert ['Groovy speaks.''Java speaks.''Scala speaks.'] == list.collect{ it.speak() }    
  17.   
  18. // We can also use the spread-dot operator to access   
  19. // properties, but we don't need to, because Groovy allows   
  20. // direct property access on list members.   
  21. assert ['Groovy''Java''Scala'] == list*.lang   
  22. assert ['Groovy''Java''Scala'] == list.lang  
Supplement: 
Groovy User Guide - Operators 
Dynamic object orientation - Using power features

沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...