0

I wonder if it is possible to do something like the following:

import scala.reflect.runtime.universe._
class Bar[T]
def foo[T]()(implicit ctag: reflect.ClassTag[T]) { 
  val clazz = classOf[Bar[ctag.runtimeClass.asInstanceOf[Class[T]]]] 
}

Here the Scala compiler complains:

error: stable identifier required, but ctag.runtimeClass found.

Is there a way to get the class type with type parameters inserted from the runtime type information available in the function?

Philosophus42
  • 472
  • 3
  • 11

2 Answers2

6

Is there a way to get the class type with type parameters inserted from the runtime type information available in the function?

classOf[Bar[T]] works for a very simple reason: it doesn't insert any runtime information! classOf[Bar[T]], classOf[Bar[String]], classOf[Bar[Int]], classOf[Bar[_]] are all the same; that's what type erasure means in JVM context (to avoid misleading, I prefer always using classOf[Bar[_]] where possible). Note that there is actually a single exception: if Bar is Array, because classOf[Array[Int]] and classOf[Array[Object]] (e.g.) are different!

classOf[T] obviously would need runtime information and so it doesn't work.

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

Thanks to the comment by @Mr. V I realized that its actually easier than I initially thought:

import scala.reflect.runtime.universe._
class Bar[T]
def foo[T]() { 
  val clazz = classOf[Bar[T]] 
}
Philosophus42
  • 472
  • 3
  • 11