一个如何(以一种很好的方式)组合两个Scala match's?
首先,我必须测试Option是否为有效值:
myOption match {
case Some(op) =>
doSomethingWith(op)
case None =>
handleTheError()
然后,如果op有效,我想测试另一种模式:
Path(request.path) match {
case "work" => {
println("--Let's work--")
}
case "holiday" => {
println("--Let's relax--")
}
case _ => {
println("--Let's drink--")
}
}
我可以这样合并它们:
myOption match {
case Some(op) =>
doSomethingWith(op)
Path(request.path) match {
case "work" => {
println("--Let's work--")
}
case "holiday" => {
println("--Let's relax--")
}
case _ => {
println("--Let's drink--")
}
}
case None =>
handleTheError()
但是,感觉草率。有没有更好的方法将它们以某种方式组合在一起。
更新资料
抱歉,我应该解释得更好。我实际上是在尝试找出是否存在用于简化(或分解)这些控制结构的已知模式。例如(想象这是真的):
x match {
case a => {
y match {
case c => {}
case d => {}
}
}
case b => {}
}
等于
x -> y match {
case a -> c => {}
case a -> d => {}
case b => {}
}
我只是在徘徊,是否有人已经确定了一些控制流的重构模式,就像代数中的
2(x + y) = 2x + 2y
最佳答案
你可以做
myOption map { success } getOrElse handleTheError
或使用
scalaz
,myOption.cata(success, handleTheError)
其中
success
类似于def success(op: Whatever) = {
doSomethingWith(op)
Path(request.path) match {
case "work" => println("--Let's work--")
case "holiday" => println("--Let's relax--")
case _ => println("--Let's drink--")
}
}
更新资料
您的伪代码
x -> y match {
case a -> c => {}
case a -> d => {}
case b => {}
}
可以从字面上翻译为scala
(x, y) match {
case (a, c) => {}
case (a, d) => {}
case (b, _) => {}
}
如果内部匹配器只有很少的选项(在这种情况下为
c
和d
),它看起来不错(这可能就是您想要的),但是它会导致代码重复(重复模式a
)。因此,通常我更喜欢map {} getOrElse {}
或较小功能上的模式匹配器分隔。但我重复一遍,在您的情况下,这看起来很合理。
关于scala - 将两个匹配模式合而为一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9500906/