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.
接著來看範例代碼:
- // 如果 key not exist:
- // - Key is string in number with default value = 42
- // - Key is Integer with default value = 0
- // - Others with default value = 'Groovy rocks!'
- def m = [start: 'one'].withDefault { key ->
- if(key instanceof Integer) return 0
- else key.isNumber() ? 42 : 'Groovy rocks!'
- }
- assert 'one' == m.start
- assert 42 == m['1']
- assert 0 == m[3]
- assert 'Groovy rocks!' == m['I say']
- assert 4 == m.size()
- // We can still assign our own values to keys of course:
- m['mrhaki'] = 'Hubert Klein Ikkink'
- assert 'Hubert Klein Ikkink' == m.mrhaki
- assert 5 == m.size()
* [ In Action ] The collective Groovy datatypes - Working with maps
沒有留言:
張貼留言