5

我有一个密封的特征:

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 扩展了 Function,这意味着我不能将我的 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 库中是否有任何等价物?

4

3 回答 3

5

你可以使用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))
于 2018-02-02T17:17:31.337 回答
4

我通常会这样做:

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 */
}
于 2015-07-15T09:17:12.553 回答
2

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

def handleMessage: PartialFunction[ActorMessage,Unit] = {
    case AddX(x) => ...
    case RemoveX(x) => ...
}
于 2015-07-15T09:08:31.547 回答