Scala case class 在接收方法中不匹配(在 akka actors 中)
Scala case class is not matched in receive method (in akka actors)
我有这样的东西:
class ProbeActor extends Actor {
case class Probe(messageKey: String)
def receiveProbe: Receive = {
case Probe(probeKey) => println("Good probe: "+probeKey)
case x => println("Bad probe: "+ x)
}
final override def receive = receiveProbe orElse receiveOther
def receiveOther: Receive = {
case _ => println("Other")
}
}
我这样称呼它:
class Prober extends ProbeActor {
val definite = ActorSystem("ProbeTest").actorOf(Props[ProbeActor], name = "probed")
implicit val timeout = Timeout(5 second)
val future = definite ? Probe("key")
}
我希望应该打印文本 "Good probe: key"
,但我得到 "Bad probe: Probe(key)"
。
注意:如果我把Probe
外壳class放在外面,就可以正常工作了。
经过更多搜索,我在 scala-lang.org 上找到了答案:
I think the underlying misconception is about the identity of nested
class types.
In
class A { class B }
each new instance of class A x creates a new type x.B. And if you do
the plain pattern match inside of A you are referring to the specific
instance of the type B this.B.
一种在 Probe
上进行模式匹配而不将其移出 class 的方法是
case probe: ProbeActor#Probe => println("Good probe: "+probe.messageKey)
当然,把它移到外面(比如移到伴生对象)是更好的解决办法;正如 Archeg 提到的,特别是在 Akka 中,以避免直接引用演员。
我有这样的东西:
class ProbeActor extends Actor {
case class Probe(messageKey: String)
def receiveProbe: Receive = {
case Probe(probeKey) => println("Good probe: "+probeKey)
case x => println("Bad probe: "+ x)
}
final override def receive = receiveProbe orElse receiveOther
def receiveOther: Receive = {
case _ => println("Other")
}
}
我这样称呼它:
class Prober extends ProbeActor {
val definite = ActorSystem("ProbeTest").actorOf(Props[ProbeActor], name = "probed")
implicit val timeout = Timeout(5 second)
val future = definite ? Probe("key")
}
我希望应该打印文本 "Good probe: key"
,但我得到 "Bad probe: Probe(key)"
。
注意:如果我把Probe
外壳class放在外面,就可以正常工作了。
经过更多搜索,我在 scala-lang.org 上找到了答案:
I think the underlying misconception is about the identity of nested class types.
In
class A { class B }
each new instance of class A x creates a new type x.B. And if you do the plain pattern match inside of A you are referring to the specific instance of the type B this.B.
一种在 Probe
上进行模式匹配而不将其移出 class 的方法是
case probe: ProbeActor#Probe => println("Good probe: "+probe.messageKey)
当然,把它移到外面(比如移到伴生对象)是更好的解决办法;正如 Archeg 提到的,特别是在 Akka 中,以避免直接引用演员。