Reputation: 11788
I am trying to create basic Actors in Akka
but I found two different ways to create actors. One way is to extend akka.actor.Actor
trait and implement receive
method as shown below
import akka.actor.Actor
class HelloActor extends Actor {
override def receive: Receive = ???
}
Other way is to use object and implement apply()
method as shown below:
final case class GreetedMessage(whom: String, from: ActorRef[GreetMessage])
final case class GreetMessage(whom: String, replyTo: ActorRef[GreetedMessage])
object GreeterActor {
def apply(): Behavior[GreetMessage] = Behaviors.receive { (context, message) =>
context.log.info("Hello {}!", message.whom)
message.replyTo ! GreetedMessage(message.whom, context.self)
Behaviors.same
}
}
I would like to know which is the preferred way to create actors and if possible reason behind it.
I am assuming that extending Actor
trait is old way since it is not mentioned on Akka official site. Please englighten.
Upvotes: 2
Views: 287
Reputation: 20551
It should be noted that neither of your examples creates an actor: that's the job of the ActorSystem
. The examples define actors.
The first method for defining an actor is the "classic" untyped Actor API.
The second method is one of the two APIs for typed actors (specifically the "functional" style API).
The Akka docs say:
For new projects, we recommend using the new [typed] Actor APIs.
The classic APIs are still fully supported and will likely be for a long time.
There is also an OO-style API for defining a typed actor:
class GreeterBehavior(context: ActorContext[GreetMessage]) extends AbstractBehavior[GreetMessage](context) {
override def onMessage(message: GreetMessage): Behavior[GreetMessage] = {
context.log.info("Hello {}!", message.whom)
message.replyTo ! GreetedMessage(message.whom, context.self)
this
}
}
Edit to add: the classic API is fully documented, e.g. Akka docs for Actors.
The typed APIs allow the compiler to validate at least some of the messaging protocol. If you have an ActorRef[Foo]
you can only send messages which are Foo
s (including subtypes of Foo
) to the actor. It's also possible to validate that the actor's behavior covers all messages it could possibly receive.
Upvotes: 3