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:

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:

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

Why is my Akka Actor getting “deadLetters” as sender?

That is a question that kept my busy for almost an hour… I had an Actor defined like this (simplified, of course):

trait Foo { self: Actor =>
    []
}

class Bar extends Actor with Foo {
    []
    def receive = {
        case x => sender ! x
    }
}

Weirdly enough, when I was sending messages to that actor, the responses always came from the deadLetters Actor belonging to my actor system. The reason for this behavior was the fact that I used self as the name for the Foo trait’s self-type, because “There is already an implicit val self defined in Actor which refers to an actor’s own ActorRef”, and if you override that, well, it breaks.

Therefore, if I change my trait to read something like this

trait Foo { actor: Actor =>
    []
}

everything works as expected.

Multiple unapply methods for pattern matching in Scala

TLDR: Take my directly to the solution.

I found this nice trick on the Scala forums. Lets imagine we have a case class such as the following:

case class Foo(a:String, b:String, c:String = null, d:String = null)

This case class, as you probably know, can now be “pattern matched” like this:

Foo("foo", "bar", "baz", "wobble") match {
    case Foo("foo", b, _, _) => b
    case _ => "What?"
}

But what if, most of the time, you only need the first two arguments, and the others are mostly irrelevant for your pattern matching. You wouldn’t want to write Foo(a, _, _ ,_) all the time, right? One possibility would be to write the unapply(x:Foo) method yourself:

class Foo(val a:String, val b:String, val c:String = null, val d:String = null)

object Foo {
    def unapply(x:Foo): Option[(String, String)] = Some(x.a, x.b)
}

new Foo("foo", "bar", "baz", "wobble") match {
    case Foo("foo", b) => b
    case _ => "What?"
}

But what if you would like to use both unapply methods at some point? In that case you have to define multiple objects with different unapply methods, because unfortunately, unlike apply, unapply can’t be overloaded (because it always takes the the same argument).

So here is my approach to multiple unapply methods:

case class Foo(val a:String, val b:String, val c:String = null, val d:String = null)

object Foo_ {
    def unapply(x:Foo): Option[(String, String)] = Some(x.a, x.b)
}

new Foo("foo", "bar", "baz", "wobble") match {
    case Foo_("foo", b) => b
    case Foo(a, _, _, d) => (a, d)
    case _ => "What?"
}

While it isn’t exactly awesome because you have to introduce a new object Foo_, I like it better than always having to write out all 4 (or more) parameters.

If you have a better approach to this problem, please let me know :)

Paste Mode in the Scala REPL

This is going to be quick but nonetheless awesome. Activate “Paste Mode” by typing :paste in the Scala REPL:

scala> :paste
// Entering paste mode (ctrl-D to finish)

class PasteMe {
    def didThat = "hooray"
}

^D
// Exiting paste mode, now interpreting.

Have fun with Paste Mode :)

Scala Trait self-types or “How do I tell my trait where it’s going to be mixed in?”

A feature of Scala whose syntax I tend to forget are self-types, with which you can tell a trait where it is going to be mixed in, just like this:

class Foo {
    def x = 5
}

trait Bar { self: Foo =>
    def y = x + 10
}

The self: Foo => part tells the trait that it is going to be mixed into a class of type Foo and that it can therefore use all methods from this type. This is why the Bar trait is then able to call the x method from the Foo class:

scala> (new Foo with Bar).y
res4: Int = 15

Whereas the following will fail miserably:

scala> (new Object with Bar).y
<console>:10: error: illegal inheritance;
  self-type java.lang.Object with Bar does not conform to Bar’s selftype Bar with Foo
          (new Object with Bar).y

Akka Logging within a TypedActor

The basic example for an Actor (not TypedActor) that uses logging from the Akka documentation is the following:

class MyActor extends Actor {
  val log = Logging(context.system, this)
  def receive = {
    case "test" => log.info("received test")
    case _      => log.info("received unknown message")
  }
}

So one might think that it is possible to do the same within a TypedActor:

class TypedActorImpl extends TypedActorTrait {
    val log = Logging(TypedActor.context.system, this)

    def squareDontCare(i:Int, i:Int):Unit {
        log.info("Weeeee!")
        i * i // Nobody cares :(
    }
}

This breaks because “you need to provide an implicit akka.event.LogSource for the type of “this” when you call Logging” (Viktor Klang), and understandably there is no implicit defined for our TypedActorImpl. But don’t despair! There is an implicit that converts an ActorRef to a LogSource, and we can access a TypedActor‘s ActorRef by using TypedActor.context.self.

So here’s the complete working example for a TypedActor:

class TypedActorImpl extends TypedActorTrait {
    val log = Logging(TypedActor.context.system, TypedActor.context.self)

    def squareDontCare(i:Int, i:Int):Unit {
        log.info("Weeeee!")
        i * i // Nobody cares :(
    }
}

Troubleshooting

You probably used something else than TypedActor.context.self for the second parameter of Logging():

error: could not find implicit value for evidence parameter of type akka.event.LogSource[...]

You probably used TypedActor.self instead of TypedActor.context.self for the second parameter of Logging():

error: ambiguous implicit values:
both value fromString in object LogSource of type => akka.event.LogSource[String]
and value fromActor in object LogSource of type => akka.event.LogSource[akka.actor.Actor]
match expected type akka.event.LogSource[Nothing]

The bright future(s) of Scala programmers

The Scala library is pretty extensive, and I’ve only recently (about 4 months ago) started programming in Scala, so I really haven’t seen much of it yet. I was inspired to write a little something on the different Future-types available in Scala when I read this question on Stackoverflow, and while researching the topic I really learned a lot about Futures and the Scala library in general.

Continue reading