程式扎記: [ GroovyGN ] Map with Default Values

標籤

2014年4月19日 星期六

[ GroovyGN ] Map with Default Values

來源自 這裡 
Preface: 
In Groovy we can create a Map and use the withDefault() method with a closure to define default values for keys that are not yet in the map. The value for the key is then added to the map, so next time we can get the value from the map. 

接著來看範例代碼: 
  1. // 如果 key not exist:  
  2. // - Key is string in number with default value = 42  
  3. // - Key is Integer with default value = 0  
  4. // - Others with default value = 'Groovy rocks!'  
  5. def m = [start: 'one'].withDefault { key ->   
  6.     if(key instanceof Integer) return 0  
  7.     else key.isNumber() ? 42 : 'Groovy rocks!'  
  8. }  
  9.   
  10. assert 'one' == m.start  
  11. assert 42 == m['1']  
  12. assert 0 == m[3]  
  13. assert 'Groovy rocks!' == m['I say']  
  14. assert 4 == m.size()  
  15.   
  16. // We can still assign our own values to keys of course:  
  17. m['mrhaki'] = 'Hubert Klein Ikkink'  
  18. assert 'Hubert Klein Ikkink' == m.mrhaki  
  19. assert 5 == m.size()  
Supplement: 
[ In Action ] The collective Groovy datatypes - Working with maps

沒有留言:

張貼留言

網誌存檔