Is it possible (via macros, some form of Shapeless automagic or otherwise) to obtain a list of the subclasses of a sealed trait:
Sealed traits are closed: they only allow a fixed set of classes to inherit from them, and all inheriting classes must be defined together with the trait itself in the same file or REPL command.
Sealed provides exhaustive checking for our application. Exhaustive checking allows to check that all members of a sealed trait must be declared in the same file as of the source file. That means that all the possible known members of a trait that must be included are known by the compiler in advance.
Scala allows using the sealed modifier for traits, classes, and abstract classes. In the context of sealed, a class, trait, or abstract class functions the same except for the normal differences between classes and traits — for instance, an abstract class can receive parameters, and traits cannot.
You don't need any 3rd party library to do this:
sealed trait MyTrait
case object SubClass1 extends MyTrait
case object SubClass2 extends MyTrait
import scala.reflect.runtime.{universe => ru}
val tpe = ru.typeOf[MyTrait]
val clazz = tpe.typeSymbol.asClass
// if you want to ensure the type is a sealed trait,
// then you can use clazz.isSealed and clazz.isTrait
clazz.knownDirectSubclasses.foreach(println)
Output:
object SubClass1
object SubClass2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With