Getting subclasses of a sealed trait

时光总嘲笑我的痴心妄想 提交于 2019-11-26 16:05:33

问题


Is it possible (via macros, some form of Shapeless automagic or otherwise) to obtain a list of the subclasses of a sealed trait:

  • At compile time?
  • At runtime?

回答1:


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



来源:https://stackoverflow.com/questions/34534002/getting-subclasses-of-a-sealed-trait

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!