2
votes

I'm learning about Actors using Scala. I found this great implementation of The Santa Claus Problem here. However, this is using Scala Actors instead of Akka Actors. There is a particular part that I don't understand how to do with Akka Actors, starting at line 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)
    }
  }

}

I'm using this guide to migrate it to Akka Actors, and I understand that the act method should be replaced with receive. But I don't understand how to do the same loop using receive. An explanation or a sample code would be helpful

1
Can you mark the line 80 here (target line).nitishagar
@nash_ag I put a comment to be more clearapSTRK
Thanks for clarifying.nitishagar
To be clear for anyone stumbling upon this question. Akka actors are the official actors for Scala starting in Scala 2.10 and Scala actors are deprecated as of 2.11. Everyone should be using Akka actors.Gangstead

1 Answers

3
votes

You could use context.become like this:

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