简体   繁体   English

在Scala中,如何创建TypeTag [Map [A​​,B]],而只有TypeTag [A]和TypeTag [B]可用?

[英]In Scala, How to create TypeTag[Map[A,B]], while only TypeTag[A] and TypeTag[B] are available?

Assuming both type A and B are erased and unknown at run time. 假设类型A和类型B在运行时都被擦除并且未知。

Is there a way to construct TypeTag[Map[A,B]]? 有没有一种方法可以构造TypeTag [Map [A​​,B]]?

Preferrably using only explicit constructor, as in my real code both A and B are wildcard (it is possible to assign type parameters to 2 functions invoking them but why bother extracting 2 methods when they are only used once). 最好只使用显式构造函数,因为在我的真实代码中,A和B都是通配符(可以将类型参数分配给调用它们的2个函数,但是为什么只使用一次却要提取2个方法呢?

Thank you for your idea. 谢谢你的想法。 Any suggestion is appreciated. 任何建议表示赞赏。

Preferrably using only explicit constructor, as in my real code both A and B are wildcard 最好只使用显式构造函数,因为在我的真实代码中,A和B都是通配符

It isn't completely clear, but do you mean that you have tagA: TypeTag[_] and tagB: TypeTag[_] ? 尚不完全清楚,但是您是说您拥有tagA: TypeTag[_]tagB: TypeTag[_]吗? If so, then you can do 如果是这样,那么你可以做

(tagA, tagB) match {
  case (tagA: TypeTag[a], tagB: TypeTag[b]) =>
    implicit val tagA1 = tagA
    implicit val tagB1 = tagB
    typeTag[Map[a, b]]
}

Somewhat ugly and boilerplaty, but I don't think there is a better way currently (and would be happy to learn otherwise). 有点丑陋和笨拙,但我认为目前还没有更好的方法(并且很乐意学习其他方法)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM