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
  • 1
  • 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. You should load every class and check if the class extends the trait.

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

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

Michael Mior
  • 27,152
  • 8
  • 85
  • 111
Dmytro Mitin
  • 37,305
  • 2
  • 20
  • 53