Let’s say I need to provide a method with a java.lang.Class object that represents a subclass of some parent class A. I need to do this from another method that has a generic parameter with an upper type bound to A.
I thought this might work:
class A
def f(clazz: java.lang.Class[_ <: A]) = ()
def g[T <: A : Manifest] = f(classManifest[T].erasure)
But it does not:
<console>:9: error: type mismatch;
found : java.lang.Class[_$1(in method g)] where type _$1(in method g)
required: java.lang.Class[_ <: A]
def g[T <: A : Manifest] = f(classManifest[T].erasure)
^
Why can’t the compiler figure out that T is, indeed, a subclass of A? Is there anyway I can help it? Or should I approach this in a completely different manner?
It does not work because
erasurehas the typeClass[_], which is an existential type. This means thatClassobjecterasureis parametrized by some type, but it is not important which exact type this is. Theerasuredoes not have a typeClass[T]above.The method
fexpects a parameter of typeClass[_ <: A]which is some type known to be a subtype ofA. This upper bound is not necessarily ensured by theClass[_]type above.Solution: you know that the
erasurehas a proper type, it’s just that this type is not exposed in theClassManifestobject. Simply cast it:EDIT:
If you have a subclass
BofA: