qed
qed

Reputation: 23094

Different syntaxes for creating Actors in Akka

I have seen quite a few syntaxes for creating an Actor:

  system.actorOf(Props(new A(a, b)), "name")
  system.actorOf(Props(classOf[A], a, b), "name")
  system.actorOf(Props[A], "name")
  system.actorOf(A(a).props(), "name")

When should one use each of these?

If there are more, additions are welcome.

Upvotes: 2

Views: 56

Answers (1)

Andrzej Jozwik
Andrzej Jozwik

Reputation: 14649

I prefer construction with companion object like:

    object MyActor {
      def props(): Props = Props[ClientActor]
    }

    class MyActor extends Actor {
     def receive: Receive = {
        ...
     }
    }

If you need some parameters put to the actor you can use:

object MyActorHandler {
  def props(parameter: String, address: SocketAddress): Props =
    Props(classOf[ClientActorHandler], parameter, address)
}

class MyActorHandler(parameter: String, address: SocketAddress)
    extends Actor {

        def receive: Receive = {
            ...
         }
}

When you add more parameter to the Actor constructor you have all in one place.

Second suggestion: create actor by context.actorOf() from supervisor. Create actor hierarchy.For more details see Supervision and Monitoring

Upvotes: 1

Related Questions