Groovy实现Ruby的case .. when表达式

清华大佬耗费三个月吐血整理的几百G的资源,免费分享!....>>>

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')}"