我正在努力实现“简单”的行为:将模式匹配代码分成两个单独的函数。
为了清晰起见,我正在简化模型:
abstract class Animal
case object Dog extends Animal
case object Cat extends Animal
case object Bird extends Animal
case object Bat extends Animal
case object Dolphin extends Animal
我想在不同的函数上对这些进行模式匹配(因为实际代码很长),但是还有其他参数,所以 PartialFunctions 让我感到恶心......
在一个完美的世界里,我可以写:
type PF = PartialFunction[(Animal, Int, String), String]
private def processFlying(a: Animal, n: Int, loc: String): PF = {
a match {
case Bird => n + " birds found in " + loc
case Bat => n + " bats found in " + underground(loc)
}
}
private def processMarine(a: Animal, n: Int, loc: String): PF = {
a match {
case Dolphin => n + " dolphins found in " + submarine(loc)
}
}
private def processPet(a: Animal, n: Int, loc: String): PF = {
a match {
case Dog => n + " dogs found in " + loc
case Cat => n + " cats found in " + loc
}
}
def processAnimal(a: Animal, number: Int, location: String) = {
val processAll = processFlying orElse processMarine orElse processPet
processAll(a, n, location)
}
然而,这是行不通的。主要是因为我的函数中需要几个参数。“为什么你不使用元组?” 你可以说?好吧,我试过了,编译器不会停止抱怨预期类型与实际类型不同,并且与我的别名不同:(
任何帮助、提示或替代方法都会很有用!
干杯
编辑:我遵循了 Cyrille 的回答,但我还需要在比赛前进行一些工作,如下所示:
val processFlying: PF = {
// doSomething, like declare a sub-function f
{
case (b: Bird, n, loc) => f(b)
case (b: Bat, n, loc) => f(b)
}
}