Simão Martins
Simão Martins

Reputation: 1240

Create actor with default parameter value

Given the following actor class:

class MyActor(val arg: Int = 5) extends Actor {
  ...
}

How can I create an instance of MyActor that uses the default value without using the dangerous variant on Prop system.actorOf(Props(new MyActor()))?

Both the first variant system.actorOf(Props[MyActor]) and the second variant system.actorOf(Props(classOf[MyActor])) throw:

IllegalArgumentException: no matching constructor found on MyActor for arguments []

Which is unexpected since the class MyActor should have an empty constructor.

Upvotes: 1

Views: 188

Answers (1)

Sergey
Sergey

Reputation: 2900

Note that Props(new MyActor) variant is only dangerous when you're calling it within another actor (due to closing over the enclosing actor's this). To overcome the danger, define a props factory in MyActor's companion object, and specify a default parameter value for it instead of in the actor's constructor:

object MyActor {
  def props(arg: Int = 5): Props = Props(new MyActor(arg))
}
class MyActor(arg: Int) extends Actor {
  ...
}

And then

system.actorOf(MyActor.props())

Upvotes: 3

Related Questions