问题
I'm relatively new to the idea of actors, and was wondering if I could get some critique on what I am doing. For part of a project, I need to have an actor that tells a collection of listening actors the time. The listening actors must be able to be added to this actor.
Currently I have this:
import akka.actor.Actor;
import akka.actor.ActorRef;
import com.github.nscala_time.time.Imports._;
class TimeManager extends Actor {
var actors:List[ActorRef] = List();
def receive = {
case AdvanceTime() => actors foreach (_ ! DateTime.now)
case AddListener(x) => actors = x :: actors
}
}
Is there any way that I can remove the state (var actors) from this code to make it more functional?
回答1:
You can't remove state since TimeManager
should contain list of actors.
You could hide it:
class TimeManager extends Actor {
def receive = getBehavior(Nil)
def getBehavior(actors: List[ActorRef]): Receive = {
case AdvanceTime() => actors foreach (_ ! DateTime.now)
case AddListener(x) => context become getBehavior(x :: actors)
}
}
回答2:
The strength of Scala is its hybrid of OO and Functional programming, scala developer don't need hate var
, if you do, you may need choose Haskell.
In your case, I think the only thing you need to change is to make actors
as private
来源:https://stackoverflow.com/questions/17207780/how-to-properly-use-akka-actors-in-scala