6

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?

Tomasz Mularczyk
  • 34,501
  • 19
  • 112
  • 166
kpbochenek
  • 469
  • 2
  • 21

3 Answers3

5

You can use Function.unlift -

val f: Throwable => Option[String] = {
  case e: NullPointerException => Some("nah it's ok")
  case e => None
}

Future(null.toString).recover(Function.unlift(f))
// Future(Success(nah it's ok))
pyrospade
  • 7,870
  • 4
  • 36
  • 52
4

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 */
}
Chris Martin
  • 30,334
  • 10
  • 78
  • 137
  • Last example is probably what I will stick to but maybe do know if I could make my receive function to look like this: def receive = handleMessage orElse handleEvent orElse ... – kpbochenek Jul 15 '15 at 20:48
2

You can just declare handleMessage as a partial function:

def handleMessage: PartialFunction[ActorMessage,Unit] = {
    case AddX(x) => ...
    case RemoveX(x) => ...
}
Lee
  • 142,018
  • 20
  • 234
  • 287