0

For example:

I have a class foo[A] {...}, and I created an object with foo [Int], and after that I want to get the data type in A in the body of its code for some processing. When I refer to 'A' by using A.isInstanceOf[...] in the body of the class, it says value A is not found.

Is there any way to extract a specific data type of a type parameter that is passed after an object's instantiation in Scala and/or Java?

atjua
  • 541
  • 1
  • 9
  • 18

3 Answers3

4

Scala TypeTags are what you are looking for, see http://docs.scala-lang.org/overviews/reflection/typetags-manifests.html

Used as implicit the compiler takes care of "passing in" the underlIng type information on construction time. So, you can refer to that information later on ..

P.S. In older versions of Scala there was Manifest as mst pointed out ...

Martin Senne
  • 5,939
  • 6
  • 30
  • 47
1

The general answer is - it's not possible. Generics types are erased on compile stage. But you can take a look onto how scala works with Manifest (ClassTag for new scala versions)

How do I get around type erasure on Scala? Or, why can't I get the type parameter of my collections?

Is there a way to extract the item type from a Manifest[List[X]] in Scala?

Community
  • 1
  • 1
vvg
  • 6,325
  • 19
  • 36
0

In Java you can use Guava TypeToken as an alternative to Class mentioned in @JoopEggen's answer. This will let you work with different generic types more easily than using Type directly.

Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487