Hi , is there any way to get all `sealed interface...
# getting-started
s
Hi , is there any way to get all
sealed interface
implementations ? ( Maybe classes or objects )
e
if you need all recursive sealed subtypes, you'll need some sort of search algorithm; I usually use something like
Copy code
val queue = ArrayDeque(T::class.sealedSubclasses)
generateSequence(queue::removeFirstOrNull).filter(mutableSetOf<KClass<*>>()::add).onEach { queue += it.sealedSubclasses }.toList()
as an easy way to achieve that
s
Thanks @ephemient
Copy code
sealed interface MySealedInterface {
  fun doSomething()
}

object Obj1 : MySealedInterface {
  override fun doSomething() {
    println("obj1 ")
  }
}

object Obj2 : MySealedInterface {
  override fun doSomething() {
    println("obj2")
  }
}

fun main() {
  
  val queue = ArrayDeque(MySealedInterface::class.sealedSubclasses)
  val impls = generateSequence(queue::removeFirstOrNull)
    .filter(mutableSetOf<KClass<*>>()::add)
    .onEach { queue += it.sealedSubclasses }
    .toList()
  
  impls.forEach { impl ->
    impl.objectInstance!!.doSomething()
  }
}
It seems working , at least for
object
… but it seems there is no easier way… (without reflections) For example :
MySealedInterface.objects
e
since you only have one level of hierarchy, you don't need the search algorithm,
MySealedInterface::class.sealedSubclasses
would work
🙌 1
but no, there is no way aside from reflection or compile-time code generation