Scala: How to get a non-erased class instance with implicits without using asInstanceOf?

Viewed 81

I have the following Java method:

public <T> void foo(Class<T> parentClass, Class<? extends T> childClass);

I tried to use an implicit ClassTag to call the above method, but unfortunately the runtime methods returns an erased class, i.e., Class[_], which means the follow code won't work:

import scala.reflect.classTag
def bar[A: ClassTag, B <: A : ClassTag] = foo(classTag[A].runtimeClass, classTag[B].runtimeclass)

I can get around it by using asInstanceOf, but I was wondering if there's a cleaner solution. It feels really weird to me that there isn't a method that returns a non-erased Class value from a ClassTag in the standard library.

To be clear, I'm looking for an existing method (In the ClassTag class or elsewhere) with the following signature:

def unerasedRuntimeClass[A: ClassTag]: Class[A] = ???

0 Answers
Related