So what I want to do:
def foo(clazz: Class[_]): Unit = {
val int = classOf[Int]
val str = classOf[String]
val opt = classOf[Option[_]]
clazz match {
case `int` => println("INT!")
case `str` => println("STRING!")
case `opt` => foo(clazz.getTheTypeOutOfGeneric) // <- I think you get the idea
}
}
For the given clazz: Class[_ :< Option[_]]
I would want to find type with which it was created, so in the end I would get INT!
when running with type Option[Int]
. How can I do it? Do I have to use reflections?
Simply put:
Class
does not carry any information about type parameters.So for example
will return
true
. Note that the operatoreq
checks for referential equality, so these two are actually the exact same object!Try it out!
Even with reflection you won't be able to get information which is just not there.
I would recommend to move away from using
Class
values and instead use type parameters and type classes for ad-hoc polymorphism. The exact solution depends on what you are effectively trying to do.But, here is an example on how type classes work:
Output:
Try it out!
For more information I would recommend reading The Type Astronaut’s Guide to Shapeless, which (apart from teaching you about Shapeless) helps you understand more general aspects of generic programming in Scala.
I hope this helps.