开发者

scala actor message definition

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  
     开发者_JAVA技巧   case Feromone(qty) if (foundMeet == true) => sender ! Feromone(qty+1); goHome  
   }}}


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"


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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜