- def match(subject, closure) {
- def whenMap = [:], otherwise = null
- closure.when = { map -> whenMap.putAll(map) }
- closure.otherwise = { otherwise = it }
- closure.resolveStrategy = Closure.DELEGATE_FIRST
- closure()
- def result = whenMap.find { condition, value -> subject in condition }
- return result ? result.value : otherwise
- }
- def manufacturer(car) {
- match(car) {
- when "Focus": "Ford"
- when "Navigator": "Lincoln"
- when "Camry": "Toyota"
- when "Civic": "Honda"
- when "Patriot": "Jeep"
- when "Jetta": "VW"
- when "Ceyene": "Porsche"
- when "Outback": "Subaru"
- when "520i": "BMW"
- when "Tundra": "Nissan"
- otherwise "Unknown"
- }
- }
- println "The Patriot is made by ${manufacturer('Patriot')}"
- println "The QQ is made by ${manufacturer('QQ')}"
来源: http://www.phpxs.com/code/1006024/