Scala actor消息定义 [英] scala actor message definition

查看:115
本文介绍了Scala actor消息定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要为要在scala actor上检索的消息定义类吗?

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

推荐答案

您可以将其视为正常的模式匹配,如下所示.

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

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

所以,是的,您应该先定义它,对不带参数的Message使用object,对具有参数的case类使用. (正如西尔维奥·比尔曼(Silvio Bierman)所指出的,实际上,您可以使用任何可以进行模式匹配的东西,因此我对该示例进行了一些修改)

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)

以下是示例代码.

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消息定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆