Search code examples
scalatype-erasure

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.


Solution

  • 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).