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

2015-12-14 0 362
Groovy实现Ruby的case .. when表达式
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')}"  

遇见资源网 groovy Groovy实现Ruby的case .. when表达式 http://www.ox520.com/13782.html

上一篇:

已经没有上一篇了!

下一篇:

已经没有下一篇了!

常见问题

相关文章

发表评论
暂无评论
官方客服团队

为您解决烦忧 - 24小时在线 专业服务