将函数转换为部分函数scala

时间:2015-07-15 09:01:00

标签: scala akka case actor partialfunction

我有一个密封的特性:

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库中是否有任何等价物?

3 个答案:

答案 0 :(得分:3)

我通常做这样的事情:

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

答案 1 :(得分:2)

您可以将handleMessage声明为部分功能:

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

答案 2 :(得分:1)

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