在Akka中保留类型参数

编程入门 行业动态 更新时间:2024-10-25 11:33:07
本文介绍了在Akka中保留类型参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

Roland Kuhn在此帖子中已经回答了该问题。但是,尽管有几条评论要求提供详细信息,他还是不愿意分享完整的答案。

This question has kind of been answered by Roland Kuhn in this post, however, despite several comments asking for detail, he didn't bother to share the complete answer.

这就是我想要做的:我有一个包装类 case类Event [T](t:T)我将实例发送给Akka演员。然后,在该参与者的 receive 方法中,我想区分 Event [Int] 和 Event [String] ,由于类型擦除,这显然不是那么简单。

Here's what I want to do: I have a wrapper class case class Event[T](t: T) of which I send instances to an Akka actor. In the receive method of that actor, I then want to distinguish between Event[Int] and Event[String], which obviously isn't so simple due to type erasure.

Roland Kuhn在提到的帖子中分享的是确实有一种方法可以做到,即在消息中体现类型信息。所以我这样做了:

What Roland Kuhn shares in the mentioned post is that "there is exactly one way to do it", that is, embodying the type information within the message. So I did this:

case class Event[T](t: T)(implicit val ct: ClassTag[T])

尽管有人提出要求,但Roland Kuhn并没有说在然后接收方法。这是我尝试的方法。

Even though asked by different people to provide it, Roland Kuhn does not say what to actually do within the receive method then. Here's what I tried.

def receive = { case e: Event => if (e.ct.runtimeClass == classOf[Int]) println("Got an Event[Int]!") else if (e.ct.runtimeClass == classOf[String]) println("Got an Event[String]!") else println("Got some other Event!") case _ => println("Got no Event at all!") }

此这是我能想到的最好的选择,因为很难将自己的头包裹在Scala的反射丛林中。

This is the best I could come up with as it's hard to wrap one's head around Scala's reflection jungle. It's not compiling, though:

value ct is not a member of Any else if (e.ct.runtimeClass == classOf[String]) ^

因此,我要特别询问接收方法应如下所示。

Thus, I am asking specifically about what the receive method should look like.

推荐答案

修复错误事件采用类型参数 def receive = { case e: Event[_] => if (e.ct.runtimeClass == classOf[Int]) println("Got an Event[Int]!") else if (e.ct.runtimeClass == classOf[String]) println("Got an Event[String]!") else println("Got some other Event!") case _ => println("Got no Event at all!") }

代码编译。通过不查看 ClassTag 的内部,可以稍微简化一下(当然, ClassTag#equals 的实现正在比较类):

the code compiles. It can be slightly simplified by not looking inside the ClassTags (of course, the implementation of ClassTag#equals is going to compare the classes):

import scala.reflect.{ClassTag, classTag} def receive = { case e: Event[_] => if (e.ct == ClassTag.Int) // or classTag[Int] println("Got an Event[Int]!") else if (e.ct == classTag[String]) println("Got an Event[String]!") else println("Got some other Event!") case _ => println("Got no Event at all!") }

更多推荐

在Akka中保留类型参数

本文发布于:2023-10-17 10:48:52,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1500679.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:参数   类型   Akka

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!