Skip to content

Instantly share code, notes, and snippets.

@xuwei-k
Last active August 29, 2015 14:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xuwei-k/20f6b813aa0d5452198e to your computer and use it in GitHub Desktop.
Save xuwei-k/20f6b813aa0d5452198e to your computer and use it in GitHub Desktop.
ActorCompanion pattern

Recommended Practices It is a good idea to provide factory methods on the companion object of each Actor which help keeping the creation of suitable Props as close to the actor definition as possible. This also avoids the pitfalls associated with using the Props.apply(...) method which takes a by-name argument, since within a companion object the given code block will not retain a reference to its enclosing scope:

package example
import akka.actor._
abstract class ActorCompanion[A <: Actor](implicit A: reflect.ClassTag[A]) {
/** constructor parameter type for `A` */
type B
def props(param: B): Props =
Props(A.runtimeClass, param)
def create(name: String, param: B)(implicit context: ActorRefFactory): ActorRef =
context.actorOf(props(param), name)
}
libraryDependencies += "com.typesafe.akka" %% "akka-actor" % "2.3.9"
scalaVersion := "2.11.6"
package example
import akka.actor.Actor
object MyActor extends ActorCompanion[MyActor] {
final case class Param(param1: Int, param2: Boolean, param3: List[String])
override type B = Param
}
class MyActor(param: MyActor.Param) extends Actor {
override def receive = {
case message =>
println(message)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment