在下面的简化代码片段中,如果将接收功能重构了,那么它将无法按预期处理传入的消息。
package spack
import akka.actor.{Actor, ActorSystem, Props}
import com.typesafe.scalalogging.LazyLogging
object Main extends LazyLogging {
import logger._
def main(args: Array[String]): Unit = {
debug("start of main")
val system = ActorSystem("SampleSystem")
val ref = system.actorOf(Props[SampleActor])
ref ! "Hello"
debug("end of main")
Thread.sleep(Integer.MAX_VALUE)
}
}
class SampleActor extends Actor with LazyLogging {
import logger._
override def receive: Receive = {
case msg => {
debug("now calling handle")
handleMsg(msg)
}
}
def handleMsg(msg1: Any): Receive = {
case msg1 => debug(s"received msg is $msg1")
}
}
以上代码段的输出:-
22:06:17.889 [main] DEBUG spack.Main$ - start of main
22:06:18.569 [main] DEBUG spack.Main$ - end of main
22:06:18.569 [SampleSystem-akka.actor.default-dispatcher-5] DEBUG spack.SampleActor - now calling handle
我原本希望输出中也低于该行,但是不知何故,它不会来。
收到的味精是“你好”
答案 0 :(得分:1)
handleMsg
返回名为Receive
的部分函数,但不对其求值。那就是为什么没有显示输出
context.become
或
handleMsg
函数返回单位,而不是未赋值的Partial函数如下定义您的handleMsg
def handleMsg(arg: Any): Unit = arg match {
case msg => debug(s"received msg is $msg")
}
或
def handleMsg: Receive = {
case msg1 => debug(s"received msg is $msg1")
}
case msg => {
debug("now calling handle")
context become handleMsg
self ! msg
}