Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert function to partial function scala

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?

like image 830
kpbochenek Avatar asked Jul 15 '15 09:07

kpbochenek


People also ask

What is the use of partial functions in Scala?

A partial function is a function that does not provide an answer for every possible input value it can be given. It provides an answer only for a subset of possible data, and defines the data it can handle. In Scala, a partial function can also be queried to determine if it can handle a particular value.

How do you pass parameters to a Scala function?

Scala - Functions with Named Arguments Named arguments allow you to pass arguments to a function in a different order. The syntax is simply that each argument is preceded by a parameter name and an equals sign. Try the following program, it is a simple example to show the functions with named arguments.

Can a partial function be Injective?

Many properties of functions can be extended in an appropriate sense of partial functions. A partial function is said to be injective, surjective, or bijective when the function given by the restriction of the partial function to its domain of definition is injective, surjective, bijective respectively.


1 Answers

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))
like image 50
pyrospade Avatar answered Sep 22 '22 20:09

pyrospade