所以我有一个创建汽车演员的演员,我将新车添加到地图中,并且我需要从地图上向它发送已损坏的消息,我该怎么做?
var cars = Map.empty[String, ActorRef]
override def receive: Receive = {
case CreateTank(id) =>
val newTank = context.actorOf(Car.props(id,hp=100), s"tank-$id")
cars = cars + (id -> newCar)
sender() ! CarCreated(id)
case CarDestroyed(id) =>
val thisCar = cars.get(id)
thisCar ! CarDestroyed
}
答案 0 :(得分:1)
在get
上调用Map
返回Option
,因此一种方法是在查找结果上调用foreach
:
var cars = Map.empty[String, ActorRef]
def receive = {
case CreateCar(id) =>
val newCar = context.actorOf(Car.props(id, hp=100), s"car-$id")
cars = cars + (id -> newCar)
sender() ! CarCreated(id)
case CarDestroyed(id) =>
cars.get(id).foreach(_ ! CarDestroyed)
}
上述参与者在收到CarDestroyed
消息时,会向与id关联的参与者发送CarDestroyed
消息(如果存在)。
此外,我可以随意调整其他case子句,因为看来您将汽车的创建与坦克的创建混淆了。
答案 1 :(得分:0)
jeffrey是完全正确的。在地图上获取该选项,作为回报,您可以执行以下操作:
var cars = Map.empty[String, ActorRef]
override def receive: Receive = {
case CreateTank(id) =>
val newTank = context.actorOf(Car.props(id,hp=100), s"tank-$id")
cars = cars + (id -> newCar) /* i think this should be newTank becaue
it has the actor ref for the new Car actor */
sender() ! TankCreated(id)
case CarDestroyed(id) =>
val thisCar = cars.get(id)
if(thisCar.isDefined)
thisCar.get ! CarDestroyed
}