Getting subclasses of sealed trait

Is it possible (using macros, some Shapeless automagic form or otherwise) to get a list of subclasses of a sealed attribute:

  • At compile time?
  • At runtime?
+4
source share
1 answer

For this you do not need a third-party library:

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:

SubClass1 object

SubClass2 object

+10
source

Source: https://habr.com/ru/post/1622247/


All Articles