2

Suppose I have a type, Result:

trait Result[+T] {

  def getValue: T

}

and a subtype of that trait, AnyValResult:

class AnyValResult(value: AnyVal) extends Result[AnyVal] {
  override def getValue: AnyVal = value
}

I want to be able to ask Scala's reflection library for all subtypes of the Result[_] type and have it return a collection that includes AnyValResult.

I've seen lots of people ask this question, and all of them seem to say that they did it using third-party tools. This was a few years ago. Short of reverse-engineering the third-party tools, is there a way to do this that was introduced in more recent versions of Scala? I would prefer not to have to reference some random project on Github if I can do it directly with reflection.

Huitzilopochtli
  • 191
  • 2
  • 13

1 Answers1

1

Subclasses can be loaded/created dynamically at runtime (if the trait is not sealed) so generally this can't be done directly with Java or Scala reflection. This is not question of how recent the version of Scala is, this is how the JVM works. The engine should load every class and check if the class extends the trait (in principle, this can be done with classpath scanners like Reflections, ClassGraph, Burningwave etc.).

How do you find all subclasses of a given class in Java?

Is it possible to get all the subclasses of a class?


On contrary, if the trait is sealed then reflection (runtime .knownDirectSubclasses), macros (compile-time .knownDirectSubclasses) or Shapeless (type classes Generic / LabelledGeneric for Coproduct if inheritors are case classes) will work in order to find subclasses (maybe this should be run recursively)

Getting subclasses of a sealed trait

Iteration over a sealed trait in Scala?


If the trait is not sealed, you still can find at least some of subclasses with a macro traversing AST

Shapeless - How to derive LabelledGeneric for Coproduct (type class KnownSubclasses)


More details: Recursively obtain subclass(es) of a class

Dmytro Mitin
  • 48,194
  • 3
  • 28
  • 66