我有一个可以处理不同类型的消息的actor,我正在尝试使用Channel来实现类型安全:
import scala.actors._
import scala.actors.Actor._
case class Message(msg: String)
class FirstActor extends Actor {
val Chan1 = new Channel[String](this)
val Chan2 = new Channel[Int](this)
def act() {
loop {
react {
case Chan1 ! msg => println("message channel1=" + msg); sender ! None
case Chan2 ! num => println("number channel2=" + num); sender ! None
}
}
}
}
然而,编译抱怨:
<console>:46: error: type mismatch;
found : scala.actors.Channel[String]
required: scala.actors.Channel[Any]
Note: String <: Any, but class Channel is invariant in type Msg.
You may wish to investigate a wildcard type such as `_ <: Any`. (SLS 3.2.10)
case Chan1 ! msg => println("message channel1=" + msg); sender ! None
我尝试了.asInstanceOf[Channel[Any]]
,但似乎模式永远不会匹配
在Actor中使用多个频道的正确方法是什么?
我正在使用scala 2.9
由于
答案 0 :(得分:-1)
您不需要频道。尝试这样的事情:
react{
case str: String => handleString(str)
case i: Int => handleInt(i)
case _ => println(this+": wrong message")
}
显然,handleString和handleInt是你应该定义的一些私有函数。