链接部分函数时如何避免“丢失类型”错误

时间:2013-04-04 19:27:46

标签: scala akka anonymous-function partialfunction

我正在学习Scala& Akka并为它开发测试应用程序。在这个应用程序中,几乎所有actor都记录未处理的消息以便于调试:

import akka.actor._

class TestActor extends Actor with ActorLogging {
  def receive: Receive = {
    case Some(value) => // do something...
    case msg => log.debug("Unhandled message: {}.", msg)
  }
}

正如我所说,这些代码几乎存在于我的所有代理中,我开始考虑将其转化为特征:

trait LogUnhandled { this: Actor with ActorLogging =>
  def logUnhandled: Receive = {
    case msg => log.debug("Unhandled message: {}.", msg)
  }
}

并在

之后使用它
class TestActor extends Actor with ActorLogging with LogUnhandled {
  def receive: Receive = {
    case Some(value) => // do something...
  } orElse logUnhandled
}

我很想知道结构子类型是否允许我这样做,或者TestActor#ReceiveLogUnhadled#Receive会是不同的类型,但即使在此之前我也有

error: missing parameter type for expanded function
The argument types of an anonymous function must be fully known. (SLS 8.5)
Expected type was: ?

现在除了将第一个{...}块移动到单独的函数中之外,我无法想象如何避免这种情况:

class TestActor extends Actor with ActorLogging with LogUnhandled {
  def doReceive: Receive = {
    case Some(value) => // do something...
  } 

  def receive: Receive = doReceive orElse logUnhandled
}

当然,后者会做,但它有点“错过了重点”并造成其他一些副作用,比如'考虑适当的函数名而不是receive'......

所以我想知道:是否可以通过某种方式声明(Any) => Unit函数签名'来避免'缺少类型参数错误'?

1 个答案:

答案 0 :(得分:4)

class TestActor extends Actor with ActorLogging with LogUnhandled {
  def receive = ({
    case Some(value) => // do something...
  }: Receive) orElse logUnhandled
}

另请查看this。 LoggingReceive允许您执行以下操作:

class A extends Actor {
   def receive = LoggingReceive {
      case msg => ...
   }
}

所有接受/拒绝的消息都将发布到调试流中。