How to create a TypeTag manually?

In M3 you could create a type tag in a very simple way, e.g.: TypeTag[Int](TypeRef(<scala package>, <symbol of scala.Int>, Nil)). It basically meant that once a type tag is created, it is forever bound to a certain classloader (namely the one that was used to load a symbol of scala.Int in the example above).

Back then it was fine, because we considered that we could have a one-size-fits-all mirror that accomodates all classloaders. That was convenient, because you could just write implicitly[TypeTag[T]] and the compiler would use that global mirror to instantiate a Type you requested.

Unfortunately later, based on feedback, we realized that this isn’t going to work, and that we need multiple mirrors – each having its own classloader.

And then it became apparent that type tags need to be flexible, because once you write that implicitly[TypeTag[T]] the compiler doesn’t have enough information what classloader you want to use. Basically there were two alternatives: 1) make type tags path-dependent on mirrors (so that one would be forced to explicitly provide a mirror every time a type tag is requested from the compiler), 2) transform type tags into type factories, capable of instantiating themselves in any mirror. Long story short, the first option didn’t work, so we are where we are.

So currently type tags need to be created in quite a roundabout way, as outlined in https://github.com/scala/scala/blob/master/src/library/scala/reflect/base/TypeTags.scala#L143. You call a factory method defined in the companion TypeTag and provide two arguments: 1) a default mirror, where the type tag will be instantiated, 2) a type factory that can instantiate a type tag in arbitrary mirror. This is basically what the compiler did in the printout you’ve attached above.

Why I called this roundabout? Because to provide a type factory you need to manually subclass the scala.reflect.base.TypeFactory class. That’s an unfortunate limitation of Scala type system on the border between function and dependently-typed methods.

Leave a Comment