Unable to explain behavior of examples executed in scala shell

LS

I learn Scala using the "Scala Programming" by Odersky et al.

In the chapter on actors, I came across behavior that I cannot explain. More specifically, when you try to send a message to "yourself" (see also an example )

Entering 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 does not return "with the expected answer":

 resX:Any = hello 

You need to do Ctrl-C to return the shell back to my input and return a message that:

 Execution interrupted by signal. scala> self.receive {case x => x} // She 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 actually the following works:

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

My questions:

What's happening? Why does the first example not work, and the second does?!? I would like to understand the behavior of the shell a little better, since the authors of the book argue that using yourself as a recipient of actors' responses is a good debugging technique.

+4
source share
1 answer

At the time the book was written, there was only one kind of actor: streaming actors. Therefore, if self was called on different objects from the same thread, it returned the same Actor . Since Scala 2.8 (I think), this is no longer running.

The shell's job is to create anonymous classes for each input sent, 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

 object $3 { self ! "Hello" ; self.receive { case x => x } } 
+9
source

Source: https://habr.com/ru/post/1386308/


All Articles