Our library uses TypeTags, but now we need to interact with another library which requires Manifests. Is there any simple way to create a Manifest from a TypeTag?
gourlaysama's anwer uses Class[_], thus type arguments are being erased. I've come up with an implementation that preserves the type arguments here: How to maintain type parameter during TypeTag to Manifest conversion?
Here's the code:
def toManifest[T:TypeTag]: Manifest[T] = {
val t = typeTag[T]
val mirror = t.mirror
def toManifestRec(t: Type): Manifest[_] = {
val clazz = ClassTag[T](mirror.runtimeClass(t)).runtimeClass
if (t.typeArgs.length == 1) {
val arg = toManifestRec(t.typeArgs.head)
ManifestFactory.classType(clazz, arg)
} else if (t.typeArgs.length > 1) {
val args = t.typeArgs.map(x => toManifestRec(x))
ManifestFactory.classType(clazz, args.head, args.tail: _*)
} else {
ManifestFactory.classType(clazz)
}
}
toManifestRec(t.tpe).asInstanceOf[Manifest[T]]
}