Given a type declaration, I am able to resolve the type argument.
scala> reflect.runtime.universe.typeOf[List[Int]] match {case x:TypeRef => x.args}
res10: List[reflect.runtime.universe.Type] = List(Int)
For a runtime value, The same method doesn’t work.
scala> reflect.runtime.currentMirror.reflect(List(42)).symbol.toType match {case x:TypeRef => x.args}
res11: List[reflect.runtime.universe.Type] = List(B)
Is there a way to overcome the type erasure for reflected values?
An example based on TypeTag knowledge gained from reading
Scala: What is a TypeTag and how do I use it?
posted by
Eugene Burmako in the comments on your question:
This should give the output:
[UPDATE 1:]
However, if you want to be aware of the type assigned to a reference of type
Anyyou might have to opt for some sort of type aware wrapper:This should give the output:
But this solution still does not cover the case where the reference type is unknown at compile time.
[UPDATE 2:]
If the types are explicitly cast to reference of type
Any, you might have to enumerate all the possible types in a match statement in order to recover the type:This should give the output:
But this solution requires you to know (and list) all the possible types that you could receive in the
anyvalue.