Chris Grimm
Chris Grimm

Reputation: 771

How to properly use akka actors in scala

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?

Upvotes: 0

Views: 702

Answers (2)

smilingleo
smilingleo

Reputation: 121

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

Upvotes: 1

senia
senia

Reputation: 38045

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

Upvotes: 7

Related Questions