Considering the following scala program:
val arr: Seq[String] = Seq("abc", "def")
val cls = arr.head.getClass
println(cls)
val ttg: TypeTag[Seq[String]] = typeOf[Seq[String]]
val fns = ttg.tpe
.members
val fn = fns
.filter(_.name.toString == "head")
.head // Unsafely access it for now, use Option and map under normal conditions
.asMethod // Coerce to a method symbol
val fnTp = fn.returnType
println(fnTp)
val fnCls = ttg.mirror.runtimeClass(fnTp)
assert(fnTp == cls)
Since TypeTag has both Seq and String information, I would expect that fn.returnType
give the correct result "String", but in this case I got the following program output:
cls = class java.lang.String
fnTp = A
And subsequently throw this exception:
A needed class was not found. This could be due to an error in your runpath. Missing class: no Java class corresponding to A found
java.lang.NoClassDefFoundError: no Java class corresponding to A found
at scala.reflect.runtime.JavaMirrors$JavaMirror.typeToJavaClass(JavaMirrors.scala:1258)
at scala.reflect.runtime.JavaMirrors$JavaMirror.runtimeClass(JavaMirrors.scala:202)
at scala.reflect.runtime.JavaMirrors$JavaMirror.runtimeClass(JavaMirrors.scala:65)
Obviously type String was erased, leaving only a wildcard type 'A'
Why TypeTag is unable to yield the correct erased type as intended?
Seq.head
is defined asdef head: A
. Andfn
is just a method symbol of the methodhead
from a generic classSeq[A]
, it doesn't know anything about the concrete type. So itsreturnType
is exactly thatA
just as defined inSeq
.If you want to know what that
A
would be in some concreteType
, you'd have to specify that explicitly. For instance, you can useinfoIn
on the method symbol: