Just looking at Scala Akka and wondering what is the difference between the following object initialisation methods.
system.actorOf(Props[HelloActor], name = "helloactor")
and
system.actorOf(Props(new HelloActor("Fred")), name = "helloactor")
I can understand the second one, Props(new HelloActor()), but what is the first one, Props[HelloActor]? I don't know its name so can't google for it.
Props is a case class with a companion object. In Scala code you will see two major ways people will construct objects. One is with a constructor on a class. Another major way is by calling an apply() method on a companion object.
If you look at the source code of akka.actor.Props you will notice that the companion object has four apply() methods, two of which you are referencing in your code above. At time of writing their signatures are:
def apply[T <: Actor: ClassTag](): Props
def apply[T <: Actor: ClassTag](creator: ⇒ T): Props
As helpful sugar Scala allows you to call an apply method without stating the apply method so in your first example you can rewrite that as Props[HelloActor]() and the compiler inserts the apply() method for you. Next, if a method has no arguments you may omit the parenthesis. So the call becomes Props[HelloActor] as you have pointed out above.
Your second example calls the second apply() method.
As to your question about how does the real HelloActor class get instantiated that is a little more complicated. All of the explicitly defined apply() methods eventually call a special apply() method that is generated by the nature of Props being a case class. This apply calls the constructor on Props which creates an akka.actor.IndirectActorProducer. This class holds many strategies that can be used to instantiate the actor. In your simple case it eventually uses reflection to construct your actor.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With