我正在学习使用Scala的Actors。我发现了圣诞老人问题的这一伟大实施here。但是,这是使用Scala Actors而不是Akka Actors。有一个特殊的部分,我不明白如何处理Akka演员,从第80行开始:
/*(line 80)*/object Secretary extends Actor{
def act = loop(Group[Elf](3), Group[Reindeer](9))
private def addToGroup[T <% Helper](helper: T, group: Group[T]) = {
val updatedGroup = group.copy(helpers = helper :: group.helpers)
if(updatedGroup.hasSpace) updatedGroup else {
Santa ! updatedGroup
group.copy(helpers = List[T]())
}
}
// How to implement this using 'receive' with akka
private def loop(elves: Group[Elf], reindeers: Group[Reindeer]):Unit = {
react {
case Idle(reindeer: Reindeer) => loop(elves, addToGroup(reindeer, reindeers))
case Idle(elf: Elf) => loop(addToGroup(elf, elves), reindeers)
}
}
}
我正在使用此guide将其迁移到Akka Actors,我知道act方法应该用receive替换。但是我不明白如何使用receive执行相同的循环。解释或示例代码会有所帮助
答案 0 :(得分:3)
您可以像这样使用context.become
:
def receive = loop(Group[Elf](3), Group[Reindeer](9))
private def loop(elves: Group[Elf], reindeers: Group[Reindeer]): Receive = {
case Idle(reindeer: Reindeer) => context become loop(elves, addToGroup(reindeer, reindeers))
case Idle(elf: Elf) => context become loop(addToGroup(elf, elves), reindeers)
}