akka - Scala, default code for PartialFunction? -


i using akka , run code cases of partialfunction. actor supervision, have like:

val supervisorstrategy = oneforonestrategy() {   case npe: nullpointerexception => stop   case re: runtimeexception => restart } 

the way have found run code cases without having write again @ 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 , other answers (like this one) couldn't figure out alternative way 1 came with.

doesn't seem akka-specific. can combine 2 functions using andthen. specifically:

package com.example  import akka.actor.oneforonestrategy import akka.actor.supervisorstrategy.{decider, restart, stop}  object answer extends app {   val dosomething:partialfunction[throwable, throwable] = { case e =>     println(s"doing $e")     e   }    val decide:decider = {     case _:nullpointerexception => stop     case _:runtimeexception => restart   }    val strategy = oneforonestrategy()(dosomething andthen decide)    val errors = seq(new nullpointerexception, new runtimeexception)   errors map strategy.decider foreach println } 

more generally:

package com.example  object answer extends app {   val inspect:partialfunction[throwable, throwable] = { case e =>       println(s"inspecting $e")       e   }    val decide:partialfunction[throwable, string] = {     case npe:nullpointerexception => "npe!"     case iae:illegalargumentexception => "bad arg!"   }    val combined = inspect andthen decide    val errors = seq(new nullpointerexception, new illegalargumentexception)   errors map combined foreach println } 

Comments

Popular posts from this blog

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -