我目前正在研究 Scala & Akka 并为其开发测试应用程序。在这个应用程序中,几乎所有参与者都记录未处理的消息以便于调试:
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#Receive
会LogUnhadled#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
函数签名“就地”来避免“缺少类型参数错误”?