views:

129

answers:

2

Do i need to define class for message i want to retrieve on a scala actor?

i trying to get this up where am i wrong

  def act() {  
    loop {  
      react {  
        case Meet => foundMeet = true ;   goHome  
        case Feromone(qty) if (foundMeet == true) => sender ! Feromone(qty+1); goHome  
   }}}
+4  A: 

You can think it as a normal pattern matching just like the following.

match (expr)
{
   case a =>
   case b =>
}

So, yes, you should define it first, use object for Message without parameters and case class for those has parameters. (As Silvio Bierman pointed out, in fact, you could use anything that could be pattern-matched, so I modified this example a little)

The following is the sample code.

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"
Brian Hsu
That was the good answer!!I'm wondering where did you get this information.Because on the official tutorial, there not so much information.Did you read the "programming in scala" book, or another website??
BenZen
@BenZenYes, I read "programming in scala", and it says that argument of receive is a partial function. Which means you could use pattern matching on it.I recommand you that get a copy of "Programming in Scala" written by Martin Odersky, it's a great book and introduce Scala in a comperhensive way.
Brian Hsu
+2  A: 

Strictly no, you can use any object as the message value. A message could be an Int, String or a Seq[Option[Double]] if you like.

For anything but play-around code I use custom immutable message classes (case-classes).

Gr. Silvio

Silvio Bierman