ticofab ticofab - 23 days ago 6
Scala Question

Scala, default code for PartialFunction?

I am using Akka and would like to run some code for all cases of a PartialFunction. For actor supervision, I have something like:

val supervisorStrategy = OneForOneStrategy() {
case npe: NullPointerException => Stop
case re: RuntimeException => Restart
}


The only way I have found to run some code for all cases without having to write it again at every case, is:

val pf = new PartialFunction[Throwable, Directive] {
def apply(throwable: Throwable) = {
doSomething(throwable)
throwable match {
case NullPointerException => Stop
case RuntimeException => Restart
}
}

def isDefinedAt(throwable: Throwable) = true
}

val supervisorStrategy = OneForOneStrategy()(pf)


I have looked around and to other answers (like this one) but couldn't figure out any alternative way to the one I came up with.

Answer

Thanks for the other answers, but in this Akka specific situation I can't get them to work. For instance, this won't compile:

val ft = OneForOneStrategy() { x: Throwable =>
  doSomething(x)
  x match {
    case npe: NullPointerException => Stop
    case re: RuntimeException => Stop
  }
}

Error:(48, 47) type mismatch;
found   : Throwable => akka.actor.SupervisorStrategy.Directive
required: akka.actor.SupervisorStrategy.Decider (which expands to) PartialFunction[Throwable,akka.actor.SupervisorStrategy.Directive]

I am using Akka 2.4.11 and Scala 2.11.8

The only working solution for me was the way I described in the initial question.