scala actor message definition

浪尽此生 提交于 2019-12-10 19:47:12

问题


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

回答1:


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"



回答2:


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



来源:https://stackoverflow.com/questions/3019474/scala-actor-message-definition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!