Search code examples
scalapartialfunction

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: 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

Solution

  • 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.