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?
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.
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.
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.
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With