我是否需要为要在 Scala Actor 上检索的消息定义类?

我试图解决这个问题
我哪里错了

  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 =>
}

所以,是的,你应该先定义它,对没有参数的 Message 使用对象,对有参数的 case 类使用对象。 (正如 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"

关于Scala Actor 消息定义,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3019474/

10-12 00:34
查看更多