1

I want to create a function that returns the runtime representation of Scala subclasses that have the same superclass using classOf, e.g.

class C

class C0 extends C
class C1 extends C

def f(i: Int): Class[C] = {
  if (i % 2 == 0) classOf[C0]
  else classOf[C1]
}

However, the return values of classOf[Cn] give me the error Expression of type classOf[Cn] doesn't confirm to the expected type Class[C], giving me the impression that inheritance information is lost in Class[T].

I reckon ClassTags could somehow help in retaining the ereased type, but how?

bugfoot
  • 667
  • 7
  • 20

1 Answers1

5

Class[A] is invariant in A. Meaning that Class[C1] is not a subtype of Class[C] even though C1 is a subtype of C.

You can rewrite the return type to an existential type Class[_ <: C] to indicate that you know that its type parameter will be a subtype of C but you don't know which one.

def f(i: Int): Class[_ <: C] = {
  if (i % 2 == 0) classOf[C0]
  else classOf[C1]
}

I suspect (but am not 100% sure right now) that it would make sense for Class to be covariant, but Class is defined in Java where all generic classes (except arrays which are special) are invariant.

Jasper-M
  • 14,966
  • 2
  • 26
  • 37