无法解释在 scala shell 中执行的示例的行为
LS
我刚刚使用 Odersky 等人的“Scala 编程”来学习 Scala。
在关于演员的章节中,我遇到了无法解释的行为。更具体地说,当尝试向“self”发送消息时(另请参阅示例< /a>)
输入 Scala shell:
scala> import scala.actors.Actor._
import scala.actors.Actor._
scala > self ! "Hello"
scala > self.receive { case x => x }
但最后一行没有“返回”预期的答案:
resX:Any = hello
需要执行 Ctrl-C 以使 shell 重新接受我的输入并返回消息:
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}
但是以下内容实际上有效:
self ! "Hello" ; self.receive { case x => x }
我的问题是:
发生了什么事?为什么第一个示例不起作用而第二个示例起作用?!? 我想更好地理解 shell 的行为,因为这本书的作者声称使用 self 作为参与者答案的接收者是一种很好的调试技术。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在本书撰写时,只有一种演员:基于线程的演员。因此,如果在同一线程的不同对象上调用 self,它会返回相同的 Actor。从 Scala 2.8(我认为)开始,这不再成立。
shell 的工作方式是为每个发送的输入创建匿名类,因此在第一种情况下,
$1.self
与$2.self
不同,而在第二种情况下你有的情况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 sameActor
. 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
and
$1.self
is different from$2.self
, while in the second case you have