Man*_*oid 1 functional-programming scala pattern-matching
我有一个字符串选项,它也可能是空的。我编写了以下代码来处理不同的流程分支:
input match {
case Some(val) => {
val match {
case "sayHi" => "Hi"
case "sayHello" => "Hello"
case _ => extractFromAnotherInput
}
}
None => extractFromAnotherInput
}
private def extractFromAnotherInput = {
anotherInput match {
case a => ....
case b => ....
}
}
Run Code Online (Sandbox Code Playgroud)
这是在函数式语言中处理代码分支的好方法还是可以以更好的方式完成?
您不必嵌套匹配项:
input match {
case Some("sayHi") => "Hi"
case Some("sayHello") => "Hello"
case _ => extractFromAnotherInput
}
Run Code Online (Sandbox Code Playgroud)
您还可以在进行匹配之前将此输入与“another”和“strip”选项结合起来:
input.getOrElse(anotherInput) match {
case "sayHi" => "Hi"
case "sayHello" => "Hello"
case a => ...
case b => ...
}
Run Code Online (Sandbox Code Playgroud)