In Scala reflection, why reflection function on TypeTag still has type erasure?

旧城冷巷雨未停 提交于 2019-12-25 07:26:09

问题


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?


回答1:


Seq.head is defined as def head: A. And fn is just a method symbol of the method head from a generic class Seq[A], it doesn't know anything about the concrete type. So its returnType is exactly that A just as defined in Seq.

If you want to know what that A would be in some concrete Type, you'd have to specify that explicitly. For instance, you can use infoIn on the method symbol:

scala> val fnTp = fn.infoIn(ttg.tpe)
fnTp: reflect.runtime.universe.Type = => String

scala> val fnRetTp = fnTp.resultType
fnRetTp: reflect.runtime.universe.Type = String


来源:https://stackoverflow.com/questions/37714572/in-scala-reflection-why-reflection-function-on-typetag-still-has-type-erasure

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!