将函数转换为部分函数scala

convert function to partial function scala

我有一个密封的特性:

sealed trait ActorMessage
case class AddX(x: Int) extends ActorMessage
case class RemoveX(x: Int) extends ActorMessage

我还有一个功能可以处理所有消息并警告我非穷尽匹配:

def handleMessage: ActorMessage => Unit = {
  case AddX(x) => ...
  case RemoveX(x) => ...
}

Actor 需要一个 PartialFunction[Any, Unit]。 PartialFunction extends Function 这意味着我不能将我的函数分配给 PartialFunction。

我写了简单的转换器:

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])
}

但是有更好的方法吗?或者标准 scala 库中是否有任何等效项?

您可以将 handleMessage 声明为部分函数:

def handleMessage: PartialFunction[ActorMessage,Unit] = {
    case AddX(x) => ...
    case RemoveX(x) => ...
}

我经常这样做:

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 */
}

等效地,使用您的 handleMessage 函数:

override def receive = {
  case m: ActorMessage => handleMessage(m)
  case m => /* log a warning */
}

你可以使用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))