用于向 Scala Actor 发送消息的符号或案例类?
在 Scala actor 示例中,我看到无参数消息被发送到 actor(例如 this< /a>),case 类
(或 case 对象
)已创建,然后用作消息。符号也同样有效,看起来更整洁,而且在读了一本关于 Erlang 的书后,看起来更自然。我认为符号相等适用于远程参与者。
对于带有参数的消息,案例类是显而易见的选择,所以消息类型之间的一致性也许是一个问题?
有什么理由选择这两种方法吗?
In the Scala actor examples I have seen where a parameterless message is sent to an actor (such as this), case class
es (or case object
s) have been created and then used as messages. Symbols work just as well and look a bit neater and, after reading a book on Erlang, seem more natural. I assume that symbol equality would work for remote actors.
For messages with parameters case classes would be the obvious choice, so perhaps consistency between message types is one issue?
Are there any reasons to go for either approach?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
简短的答案是编译时检查。
即使符号可以用作消息,并且它们比 case 对象更简洁(无需定义它们),编译器也无法检测到拼写错误的符号,并且您将很难弄清楚为什么参与者在以下情况下没有收到特定消息:他们应该这样做。
如果使用案例类和/或对象作为消息,编译器会告诉您在程序执行之前是否尝试发送和/或接收不存在的消息。
The short answer is compile-time checking.
Even thought symbols can be used as messages and they are even more succinct than case objects (no need to define them), compiler can not detect the misspelled symbols and you will have a hard time figuring out why actors aren't receiving specific messages when they are supposed to.
If case classes and/or objects are used as messages, compiler will tell you if you are trying to send and/or receive non-existent messages before the program is even executed.
我不认为
Symbol
可以替代使用case
类。事实上,我并不完全确定Symbol
到底有什么用途,因为它缺乏其他语言(例如 Ruby、Smalltalk)中符号的功能 - 它只是一个内部字符串。例如,在标准拍卖示例中,很难看出如何仅使用符号来表示出价/报价的复杂性。
至于
case
objects,我也相信它们比符号更可取。例如,它们可以是特征等的实例,从而提供功能。I don't think that
Symbol
s are a substitute for usingcase
classes. In fact, I'm not entirely sure what useSymbol
is at all, given it lacks the power of symbols in other languages (e.g. Ruby, Smalltalk) - it's just an interned String.For example, in the standard auction example, it's difficult to see how you would represent the complexity of a bid / offer using symbols alone.
As for
case
objects, I also believe that these are preferable to symbols. For example, they can be instances oftrait
s etc, and hence supply functionality.