简体   繁体   中英

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.

Is there a way to construct 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).

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

It isn't completely clear, but do you mean that you have tagA: TypeTag[_] and 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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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