The way you wrote it is not very reliable if you have a more complex class hierarchy, because if you have a class D <: C , then classOf[D] != classOf[C] . So you still don't want the pattern to match. But you could; you cannot call classOf[X] in the middle of matching the pattern, but you can
def zFor[T <: A : Manifest]: Option[Z] = { val ClassB = classOf[B] val ClassC = classOf[C] manifest[T].erasure match { case ClassB => Some(new Z1) case ClassC => Some(new Z2) case _ => None } }
while you are sure that you are in a situation where you only need to discover the leaves of the class hierarchy. (You should probably make sure by noting B and C final .)
Alternatively, you can use isAssignableFrom to run a run-time test:
def zFor2[T <: A : Manifest]: Option[Z] = { manifest[T].erasure match { case x if classOf[B].isAssignableFrom(x) => Some(new Z1) case x if classOf[C].isAssignableFrom(x) => Some(new Z2) case _ => None } }
and now
class D extends C(5) {} scala> zFor[D] res5: Option[Z] = None scala> zFor2[D] res6: Option[Z] = Some( Z2@2556af33 )
source share