John Sullivan
John Sullivan

Reputation: 1311

Scala: Getting a TypeTag on an inner type

I'm trying to get a TypeTag or ClassTag for an inner type to provide a ClassTag to a method with type parameters. Specicfically, I have

trait Baz
trait Foo { type Bar <: Baz }

and I'd like to do something like

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

but I get a 'no typetag available' error. My ultimate goal is to provide ClassTags to 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])

Upvotes: 3

Views: 532

Answers (1)

user1804599
user1804599

Reputation:

Normally you can get type tags and class tags from inner types just fine. However, Foo#Bar is an abstract type. Neither type tags nor class tags can be acquired 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

Upvotes: 5

Related Questions