类型安全的 Scala 参与者
有没有什么方法可以指定参与者可以接受什么类型的消息,并在任何尝试向其发送其他类型的消息时给出编译错误?
Is there any way to specify what type of message an actor can accept and give a compile error if anything tries to send it some other type?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不知道是否能解答你的问题,但希望能给你一些想法。也许您正在寻找类似 Typed Actors 的内容来自 Akka 项目:
因此,您定义接口和实现,然后将它们注册为参与者。 Akka 将为您的界面创建代理,该代理仍然在底层使用 Actor 模型。您仍然可以使用以下消息传递样式:
Not sure whether it answers your question, but I hope it will give you some ideas. Maybe you are searching for something like Typed Actors from Akka project:
So you define interface and implementation and then register them as actor. Akka will create proxy for your interface that still use actor model under the hood. And you still able to use following message passing styles:
我认为答案就在@mkneissl提到的帖子中:
“常见的做法是在 Actor 的伴生对象中声明 Actor 可以接收哪些消息,这使得更容易知道它可以接收什么。”
一个例子会很有用......
I think the answer is in the post referred to by @mkneissl :
"The common practice is to declare what messages an Actor can recieve in the companion object of the Actor, which makes it very much easier to know what it can receive."
An example of that would be useful...
虽然类型化的 Actor 确实在某种程度上解决了问题,但您必须记住,这仅提供部分静态类型安全 - 您仍然通过 typedActorOf(.typedActorOf(. ..) 调用,这就是动态性蔓延和静态正确性丢失的地方 - 如果底层引用最终指向一个实际上不遵守类型化接口的参与者,那么你就会遇到一个错误; Akka 不会尝试运行时验证谁“支持”类型化引用,因此类型化消息最终会被发送到无法(正确)响应它们的参与者。
总而言之,据我所知,使用 Akka 实现完全(?)静态类型安全的唯一方法是使用类型化通道:http://letitcrash.com/post/45188487245/the-second-step-akka-typed-channels。
While typed actors do solve the problem to some extent, you have to keep in mind that this only provides partial static type safety — you are still silently doing a dynamic cast from an untyped actor to a typed one by that
typedActorOf(...)
call, and that's where the dynamicity creeps in and static correctness is lost — if the underlying ref turns out to point to an actor that does not actually obey the typed interface, you have a bug; Akka attempts no runtime verification of who's "backing" the typed ref so typed messages end up being sent to actors that can't (properly) respond to them.All in all, to my best knowledge, the only way to go about achieving complete (?) static type safety with Akka is to use Typed Channels: http://letitcrash.com/post/45188487245/the-second-step-akka-typed-channels.