2010-06-11 152 views
3

我需要爲我想要在scala演員上檢索的消息定義類嗎?斯卡拉演員消息定義

我試圖讓這件事 我在哪裏錯了

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

回答

7

你可以把它作爲一個正常的模式匹配,就像下面。

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

所以,是的,你應該首先定義它,使用消息對象沒有參數和case類爲那些有參數。 (正如西爾維奧·比爾曼所指出的,事實上,你可以使用任何可以模式匹配的東西,所以我稍微修改了這個例子)

以下是示例代碼。

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" 
+0

這是很好的答案! 我想知道你從哪裏得到這些信息。 因爲在官方教程中,沒有那麼多的信息。 您是否閱讀過「scala編程」書籍或其他網站? – benzen 2010-06-11 12:10:03

+0

@ BenZen 是的,我讀了「scala編程」,它說接收的參數是一個部分函數。這意味着你可以使用模式匹配。 我建議你獲得Martin Odersky編寫的「Programming in Scala」的副本,這是一本很棒的書,並以全面的方式介紹Scala。 – 2010-06-12 00:12:11

4

嚴格來說不,您可以使用任何對象作爲消息值。如果您願意,消息可以是IntStringSeq[Option[Double]]

對於除遊戲碼外的任何東西,我使用自定義不可變消息類(case-classes)。