Scala: getting a TypeTag for an inner type

I'm trying to get TypeTag

or ClassTag

for an internal type to provide a ClassTag

method with type parameters. Specifically, I have

trait Baz
trait Foo { type Bar <: Baz }

      

and I would like to do something like

import scala.reflect.runtime.universe._
import scala.reflect._
typeTag[Foo#Bar] // or maybe
classTag[Foo#Bar]

      

but I get the error "no typetag available". My ultimate goal is to provide ClassTag

something like this

import scala.reflect.ClassTag
class Doer[A,B]()(implicit ctA:ClassTag[A], ctB:ClassTag[B])
object Fooer extends Doer[Foo, Foo#Bar]()(classTag[Foo], classTag[Foo#Bar])

      

+3


source to share


1 answer


You can usually get type tags and class tags from internal types. However, it Foo#Bar

is an abstract type. Tag tags and class tags cannot be derived from abstract types. You can get a weak type tag instead:



scala> weakTypeTag[Foo#Bar]
res1: reflect.runtime.universe.WeakTypeTag[Foo#Bar] = WeakTypeTag[Foo#Bar]

scala> class Doer[A, B]()(implicit wttA: WeakTypeTag[A], wttB: WeakTypeTag[B])
defined class Doer

scala> new Doer[Foo, Foo#Bar]()
res2: Doer[Foo,Foo#Bar] = Doer@1994551a

      

+5


source







All Articles