Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't explain behaviour of examples executed in the scala shell

L.S.

I'm just learning Scala using "Programming in Scala" by Odersky et al.

In the chapter on actors I ran in to behaviour I can't explain. More specifically when trying to send a message to 'self' (see also example)

Entering in the Scala shell:

scala> import scala.actors.Actor._  
import scala.actors.Actor._
scala > self ! "Hello"

scala > self.receive { case x => x }

But the last line doesn't 'return' with the expected answer:

resX:Any = hello

In need to do a Ctrl-C to get the shell back accepting my input and returns the message that:

Execution interrupted by signal.

scala> self.receive {case x => x}
// She's gone rogue, captain! Have to take her out!
// Calling Thread.stop on runaway Thread[Thread-54,5,main] with offending code:
// scala> self.receive {case x => x}

But the following actually works:

self ! "Hello" ; self.receive { case x => x }

My questions is:

What's happening? Why doesn't the first example work and the second does?!? I would like to understand the behaviour of the shell a bit better as the authors of the book claim that using self as the recipient of answers of actors is a nice debugging technique.

like image 347
nanitous Avatar asked Jan 19 '23 01:01

nanitous


1 Answers

At the time the book was written, there was only one sort of actors: thread-based actors. So if self was called on different objects from the same thread, it returned the same Actor. Since Scala 2.8 (I think) this no longer holds.

The way shell works is by creating anonymous classes for each sent input, so in the first case you have

object $1 {
  self ! "Hello"
}

object $2 {
  self.receive { case x => x }
}

and $1.self is different from $2.self, while in the second case you have

object $3 {
  self ! "Hello" ; self.receive { case x => x }
}
like image 180
Alexey Romanov Avatar answered Jan 30 '23 20:01

Alexey Romanov