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?
If you try naively to summon a Manifest
when a TypeTag
is present, the compiler will give you a hint as to the solution:
import reflect.runtime.universe._
import reflect.ClassTag
def test[A : TypeTag] = manifest[A]
error: to create a manifest here, it is necessary to interoperate with the type
tag `evidence$1` in scope.
however typetag -> manifest conversion requires a class tag for the corresponding
type to be present.
to proceed add a class tag to the type `A` (e.g. by introducing a context bound)
and recompile.
def test[A : TypeTag] = manifest[A]
^
So if you have a ClassTag
in scope, the compiler will be able to create the necessary Manifest
. You have two options:
Add a second context bound everywhere TypeTag
is, as in:
def test[A : TypeTag : ClassTag] = manifest[A] // this compiles
Or first convert the TypeTag
to a ClassTag
, then ask for a Manifest
:
def test[A](implicit ev: TypeTag[A]) = {
// typeTag to classTag
implicit val cl = ClassTag[A]( ev.mirror.runtimeClass( ev.tpe ) )
// with an implicit classTag in scope, you can get a manifest
manifest[A]
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With