user16647
user16647

Reputation: 165

Scala actors being passed as parameters to other actors

I was experimenting with actors in Scala. But I'm very curious about two things. (1) Is there a way to declare an actor as a parameter to itself (as in the following code) without the use of another actor? (I've seen the Producer/Consumer example and many others, that declare an actor of one kind and use that as a parameter to another.) Also, (2) the statement in the main method that declares a new actor, but uses "_ : Actor" ... what does that mean? It compiles (which I didn't expect) but doesn't work as I intended (which I expected).

import scala.actors.Actor;
import Actor._;

// Code for declaring methods that actors can send and receive

class Actor1(subact: Actor) extends Actor {
  def act: Unit = {
    println("doing stuff...")
    while (true) {
      // Code here for methods ...
    }
  }
  this.start()
}

object foo {
  def main(args: Array[String]) : Unit = {
    val i = new Actor1(_ : Actor)
  }
}

Upvotes: 1

Views: 122

Answers (1)

drexin
drexin

Reputation: 24413

(1)

Yes, that is possible:

class Foo(actor: => Actor) extends Actor {
  def act {
    loop {
      react {
        case x: String => actor ! x
      }
    }
  }
}

lazy val foo = new Foo(foo)

foo.start

foo ! "bar"

But it doesn't make much sense, as you always have a reference to the actor inside of itself ;-). And in this case it would just be like an infinite loop.

(2) is very simple, you create a partially applied function:

scala> class Foo(actor: Actor) {
     | println(actor.toString)
     | }
defined class Foo

scala> new Foo(_: Actor)
res0: (scala.actors.Actor) => Foo = <function1>

If you would store it into a variable and later call it with an actual instance of an Actor you would get an instance of your Actor1 class.

Upvotes: 3

Related Questions