在Akka Scala中访问消息对象实例

hot*_*oup 1 scala akka

在Akka的Scala API中,如何访问已发送给角色的消息对象?也许这个对象比一些琐碎的字符串要复杂得多,也许它包含我要检查和使用的属性:

case class HotSauce(amount : Double, capcaisin : Double)

class SpicyMeatball extends Actor {
  override def receive: Receive = {
    case HotSauce =>
      // How do I get access to the HotSauce message instance?
      val capcaisin = ???.getCapcaisin()
  }
}
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

And*_*kin 5

通常,您定义类似单独的小协议之类的东西,并带有案例类枚举可接受的消息。例如,在您的情况下,可能是

sealed trait SMP // spicy meatball protocol
case class HotSauce(amount: Double, capcaisin: Double) extends SMP
case class Foobar(baz: String, wambo: Int) extends SMP
Run Code Online (Sandbox Code Playgroud)

然后receive围绕它进行结构化:

override def receive: Receive = {
  case HotSauce(n, capcaisin) => /* do something with `n` and `capcaisin` */
  case Foobar(b, w) => /* do sth. with `b` and `w` */
}
Run Code Online (Sandbox Code Playgroud)

如果你HotSauce不是一类的情况下,您仍然可以通过类型模式匹配:

override def receive: Receive = {
  case hs: HotSauce => 
    val capcaisin = hs.getCapcaisin()
    // do sth. with it
}
Run Code Online (Sandbox Code Playgroud)