Scala: TypeTag generated for an internal type within a class does not match the type

If the class contains an inner class and TypeTag

, since it is generated within that class, the generated one TypeTag

will contain an inner type that is "container-relative" and does not match the TypeTag

generic type parameter. For example:.

scala> import scala.reflect.runtime.{universe => ru}
scala> class A { class B; val t = ru.typeTag[B] }
scala> val x = new A
scala> x.t
res0: reflect.runtime.universe.TypeTag[x.B] = TypeTag[A.this.B]

      

Here, x.t

there TypeTag[x.B]

, but actually contains a different type: A.this.B

. The problem is that although the inner type is different for each instance A

, the type inside TypeTag

remains the same:

scala> val y = new A
scala> y.t
res1: reflect.runtime.universe.TypeTag[y.B] = TypeTag[A.this.B]

scala> x.t.tpe =:= y.t.tpe
res2: Boolean = true

scala> ru.typeOf[x.B] =:= ru.typeOf[y.B]
res3: Boolean = false

      

Is this behavior a project or can this issue be resolved in later versions (my version is 2.11.7)?

One way to solve this problem is to create a TypeTag

container outside the class:

scala> def tt(a: A)(implicit t: ru.TypeTag[a.B]) = t

scala> tt(x)
res6: reflect.runtime.universe.TypeTag[x.B] = TypeTag[x.B]

scala> tt(y)
res7: reflect.runtime.universe.TypeTag[y.B] = TypeTag[y.B]

      

Are there any other workarounds?

+3


source to share





All Articles