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中保留类型参数
发布评论