我是否需要为要在 scala 演员上检索的消息定义类?
我试图解决这个问题我错在哪里
def act() {
loop {
react {
case Meet => foundMeet = true ; goHome
case Feromone(qty) if (foundMeet == true) => sender ! Feromone(qty+1); goHome
}}}
您可以将其视为普通模式匹配,如下所示。
match (expr)
{
case a =>
case b =>
}
所以,是的,你应该先定义它,对没有参数的消息使用对象,对有参数的使用案例类。(正如 Silvio Bierman 指出的那样,事实上,您可以使用任何可以进行模式匹配的东西,所以我稍微修改了这个示例)
以下是示例代码。
import scala.actors.Actor._
import scala.actors.Actor
object Meet
case class Feromone (qty: Int)
class Test extends Actor
{
def act ()
{
loop {
react {
case Meet => println ("I got message Meet....")
case Feromone (qty) => println ("I got message Feromone, qty is " + qty)
case s: String => println ("I got a string..." + s)
case i: Int => println ("I got an Int..." + i)
}
}
}
}
val actor = new Test
actor.start
actor ! Meet
actor ! Feromone (10)
actor ! Feromone (20)
actor ! Meet
actor ! 123
actor ! "I'm a string"
严格来说,您可以使用任何对象作为消息值。一条消息可以是一个Int
,String
或者Seq[Option[Double]]
如果你喜欢的话。
除了玩转代码之外,我使用自定义的不可变消息类(案例类)。