Sunday, July 06, 2008

Using Scala Actors

I'm assuming (maybe incorrectly) that most of the Actors that will be written will simply want to react to messages, forever. Something like this:

val reactor = new Actor(){
def act() {
case msg => ...

Given that assumption, it seems like it would be nice just to define whats in the react portion of the code. The rest is redundant. This is pretty simple. First, I created a simple little factory called Actors.

object Actors{
def newReactor( f: PartialFunction[Any,Unit] ): Actor = {
new Actor(){ def act() { loop{ react(f) } } }

and then I simply used it:

val reactor = Actors.newReactor {
case msg => println( "Got something: " + msg )

This consolidated the code outside the actual reaction from 4 lines (and 4 right brackets) to a single line (and a single right bracket).

You can also do some other interesting which allow you to keep your reaction code separate from the actual actors (you can do this using the original approach as well). You can define partial functions, and pass them into the newReactor method like this:

def normalReaction : PartialFunction[Any,Unit] = {
case x: int => println( "Got int: " + x )
case msg => println( "Got something else: " + msg )

def abnormalReaction : PartialFunction[Any,Unit] = {
case msg => println("eruhewiurhqweihu!!!!")

val normalReactor = Actors.newReactor { normalReaction }
val abnormalReactor = Actors.newReactor { abnormalReaction }

I know this is all rather simple and trivial, but I'm crazy about reducing redundancy and improving readability.