I\'m interested in creating a TypeTag manually (since 2.10M5):
object X {
import reflect.runtime.universe._
def tt[A : TypeTag](a: A) = typeTag[A] // how
Based on Get TypeTag[A] from Class[A]:
import scala.reflect.runtime.universe._
def typeToTypeTag[T](
tpe: Type,
mirror: reflect.api.Mirror[reflect.runtime.universe.type]
): TypeTag[T] = {
TypeTag(mirror, new reflect.api.TypeCreator {
def apply[U <: reflect.api.Universe with Singleton](m: reflect.api.Mirror[U]) = {
assert(m eq mirror, s"TypeTag[$tpe] defined in $mirror cannot be migrated to $m.")
tpe.asInstanceOf[U#Type]
}
})
}
For example this can be used to get the TypeTag
for a part of another TypeTag
:
def inside[A, B](tag: TypeTag[(A, B)]): (TypeTag[A], TypeTag[B]) = {
val tpes = tag.tpe.asInstanceOf[TypeRefApi].args
val tagA = typeToTypeTag[A](tpes(0), tag.mirror)
val tagB = typeToTypeTag[B](tpes(1), tag.mirror)
return (tagA, tagB)
}
This works in Scala 2.10.2:
scala> inside(typeTag[(Int, Double)])
res0: (reflect.runtime.universe.TypeTag[Int], reflect.runtime.universe.TypeTag[Double]) = (TypeTag[Int],TypeTag[Double])
The limitation of being tied to a particular Mirror
is likely not a problem as long as you don't have multiple ClassLoader
s.