🌞


Note that this blog post has been archived. Information may be out of date or incorrect.

InstantiationException when creating Akka Actor

This post might help you if you get an exception such as the following when creating an Akka Actor with actorOf(Props[SomeActor]):

[ERROR] 15:32:44.249 :: akka://.../user/foo :: akka.actor.ActorCell :: error while creating actor
    java.lang.InstantiationException: package.of.SomeActor
    at java.lang.Class.newInstance0(Class.java:340)

The reason I got this error was simply because I didn’t have a constructor with zero arguments, that is, my Actor’s class signature looked like this:

:scala:
class SomeActor(val attrs:Map[String, String] = Map()) extends Actor

I assumed that, since map has a default value, it would work just like a no-argument constructor, but that was foolish, of course. Akka invokes java.lang.Class.newInstance, which in turn calls java.lang.Class.newInstance0, which (as far as I know) is a special case of newInstance for constructors with no arguments. Given that this special case is not applicable for our Actor class, an exception is thrown. I worked around this problem like this:

:scala:
class SomeActor(val attrs:Map[String, String] = Map()) extends Actor {
    def this() = this(Map())
}