Search code examples
akkaactor

Why akka actor use ActorRef as paramater's type rather then the type itselfs?


I have read many example of definition of actors class to build a program. What I notice is all of them use ActorRef as paramaters type. For example,

class LogProcessor(dbWriter: ActorRef)
    extends Actor with ActorLogging with LogParsing {

    import LogProcessor._

    def receive = {
      case LogFile(file) =>
        val lines: Vector[DbWriter.Line] = parse(file)
        lines.foreach(dbWriter ! _)
    }
}

the dbWriter's actual type is DBWriter defined as:

class DbWriter(databaseUrl: String) extends Actor {
    val connection = new DbCon(databaseUrl)

    import DbWriter._
    def receive = {
      case Line(time, message, messageType) =>
        connection.write(Map('time -> time,
          'message -> message,
          'messageType -> messageType))
    }

    override def postStop(): Unit = {
      connection.close() 
    }
  }

At the example, why not use DbWriter as dbWriter's type?
If we use ActorRef anywhere, out program just look like a weak type system.
Besides, Akka actor use actorOf method to create child actor and it return ActorRef.I also confuse why not return the real type of the actor?


Solution

  • Some comments about actors:

    • We can create many instances of an Actor by calling actorOf or actorFor
    • We assign a different name to any actor instance we create
    • Calling actorOf will return an ActorRef that points to that instance
    • You only communicate with an Actor's instance by sending messages through its ActorRef, that way the actor instance is encapsulated and there is no way to access its internal state
    • Using the ActorRef allows you to communicate with local or remote actors
    • Each actor(child) has one parent(another actor), the parent is the one who created the actor using actorOf
    • The parent decides the supervision strategy of its children
    • Usually, you create one instance of an actor and share the resulting ActorRef with other actors who wish to communicate with that actor