lauantai 18. syyskuuta 2010

Use normal class as message receiver in Scala

I constantly encounter the following problem when writing Scala.

If you want to use normal class as receiver for messages, you have to remember to import Actor._. Otherwise compiler will complain:

error: not found: value self

Following should print "Success"

import actors.Actor
import actors.Actor._
class Example {
case class Message(sender: Actor)
val receiver = actor {
  react {
    case Message(s: Actor) => sender ! true; exit();

receiver ! Message(self)

self.receiveWithin(100) {
  case true => println("Success")
  case false => println("Failure")

I've been using this kind of "pattern" when testing message based communication between objects. It seems to be working pretty well, but tweaking of that timeout is important.