Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting subclasses of a sealed trait

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?
like image 769
NietzscheanAI Avatar asked Dec 30 '15 17:12

NietzscheanAI


People also ask

What does sealed trait mean?

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.

Why are traits sealed?

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.

What is sealed abstract class in Scala?

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.


1 Answers

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

like image 155
Max Avatar answered Sep 21 '22 09:09

Max