Partial Function pattern match split into a class and a trait
Lift uses a PartialFunction on their implementation of Comet Actors, and you usually end up with this on your class:
override def lowPriority: PartialFunction[Any,Unit] = {
case MyCaseClass1(a) => do something here
case MyCaseClass2(a) => do something here
case AlwaysPresentCaseClass => default action
}
What I'd like to do, and I'm not sure if it is even possible is to split that Partial Function so that the last case can be moved into a trait.
So when I have a new comet actor I simply do:
class MyNewComet extends MyActorTrait {
override def lowPriority: 开发者_C百科PartialFunction[Any,Unit] = {
case MyCaseClass1(a) => do something here
case MyCaseClass2(a) => do something here
}
}
And Somehow the trait MyActorTrait will have the missing
case AlwaysPresentCaseClass => default action
You can compose partial functions using the orElse
method:
val f1: PartialFunction[Any, String] = {
case 22 => "hallo"
}
val f2: PartialFunction[Any, String] = {
case "rara" => "welt"
}
val f = f1 orElse f2 // f falls back to f2 if undefined in f1
f(22)
f("rara")
Try this:
trait MyActorTrait extends /* whatever class provides lowPriority */ {
def default: PartialFunction[Any, Unit] = {
case AlwaysPresentCaseClass => default action
}
abstract override def lowPriority: PartialFunction[Any,Unit] =
super.lowPriority orElse default
}
The only problem is that you can't do MyNewComet extends MyActorTrait
. Instead, you can either have class MyNewCometDefault extends MyNewComet with MyActorTrait
, or new MyNewComet with MyActorTrait
.
精彩评论