Groovy学习笔记——实现Ruby的case .. when表达式

今天看到有人在Groovy的邮件列表上问Groovy能不能支持Ruby的case ... when表达式:
car = "Patriot"

manufacturer = case 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"
else "Unknown"
end

puts "The " + car + " is made by " + manufacturer

然后Guillaume给出了这么一段代码:
def car = "Patriot"

def manufacturer = 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 $car is made by $manufacturer"

def match(obj, closure) {
closure.subject = obj
closure.when = { value, result ->
if (value == subject)
throw new MatchResultException(result: result)
}
closure.otherwise = { return it }
closure.resolveStrategy = Closure.DELEGATE_FIRST
try {
closure()
closure.otherwise()
} catch (MatchResultException r) {
r.result
}
}

class MatchResultException extends RuntimeException {
def result
}

我不是很喜欢里面用异常来控制程序的流程,而且觉得“when "Focus", "Ford"”中间的逗号不够直观,因此就在上面的代码的基础上做了一些修改:
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 1.6下编译通过。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值