程式扎記: [ GroovyGN ] The Spread-Dot Operator

標籤

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

沒有留言:

張貼留言

網誌存檔

關於我自己

我的相片
Where there is a will, there is a way!