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:
Last active
August 29, 2015 14:18
-
-
Save xuwei-k/20f6b813aa0d5452198e to your computer and use it in GitHub Desktop.
ActorCompanion pattern
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
libraryDependencies += "com.typesafe.akka" %% "akka-actor" % "2.3.9" | |
scalaVersion := "2.11.6" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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