I have a sealed trait:
sealed trait ActorMessage
case class AddX(x: Int) extends ActorMessage
case class RemoveX(x: Int) extends ActorMessage
Also I have a function to handle all messages and warn me about non exhaustive match:
def handleMessage: ActorMessage => Unit = {
case AddX(x) => ...
case RemoveX(x) => ...
}
Actor requires a PartialFunction[Any, Unit]. PartialFunction extends Function which means I can't assign my Function to be PartialFunction.
I have written simple converter:
def liftToPartialFunction[FUND <: PFUND, B, PFUND](f: Function[FUND, B]): PartialFunction[PFUND, B] = new PartialFunction[PFUND, B] {
override def isDefinedAt(x: PFUND): Boolean = x.isInstanceOf[FUND]
override def apply(v1: PFUND): B = f(v1.asInstanceOf[FUND])
}
But is there a better way to do this? Or is there any equivalent in standard scala library?
I usually do something like this:
override def receive = {
case m: ActorMessage => m match {
// You'll get non-exhaustive match warnings here
case AddX(x) => /* ... */
case RemoveX(x) => /* ... */
}
case m => /* log a warning */
}
Equivalently, using your handleMessage
function:
override def receive = {
case m: ActorMessage => handleMessage(m)
case m => /* log a warning */
}