【问题标题】:convert function to partial function scala将函数转换为部分函数
【发布时间】:2015-07-15 09:00:59
【问题描述】:

我有一个封闭的特质:

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

【问题讨论】:

    标签: scala akka case actor partialfunction


    【解决方案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))
    

    【讨论】:

      【解决方案2】:

      我通常会这样做:

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

      【讨论】:

      • 最后一个例子可能是我会坚持的,但也许我知道我是否可以让我的接收函数看起来像这样:def receive = handleMessage orElse handleEvent orElse ...
      【解决方案3】:

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

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

      【讨论】:

      • 这不会警告我非详尽匹配。
      猜你喜欢
      • 1970-01-01
      • 2015-09-08
      • 2021-11-26
      • 1970-01-01
      • 2014-02-28
      • 2016-06-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多