Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to convert a TypeTag to a Manifest?

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?

like image 401
Alexey Romanov Avatar asked Apr 30 '14 08:04

Alexey Romanov


1 Answers

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]
    }
    
like image 134
gourlaysama Avatar answered Oct 22 '22 05:10

gourlaysama