Reputation: 5962
This doesn't work - is there any way I can keep my code generified and somehow reflect the classOf a ClassTag??
class Foo[T : reflect.ClassTag] { def foo = classOf[T] }
<console>:7: error: class type required but T found
class Foo[T : reflect.ClassTag] { def foo = classOf[T] }
It seems this should work but alas :(
Upvotes: 18
Views: 9077
Reputation: 895
Yes, that's possible.
class Foo[T: reflect.ClassTag] {
def ctag = implicitly[reflect.ClassTag[T]]
def foo: Class[T] = ctag.runtimeClass.asInstanceOf[Class[T]]
}
or shorter:
class Foo[T](implicit ctag: reflect.ClassTag[T]) {
def foo: Class[T] = ctag.runtimeClass.asInstanceOf[Class[T]]
}
Upvotes: 34