How to properly use akka actors in scala

帅比萌擦擦* 提交于 2019-12-19 12:24:00

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!