https://kotlinlang.org logo
#getting-started
Title
# getting-started
s

smallufo

08/19/2021, 3:40 PM
Hi , is there any way to get all
sealed interface
implementations ? ( Maybe classes or objects )
e

ephemient

08/19/2021, 4:14 PM
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

smallufo

08/19/2021, 4:33 PM
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

ephemient

08/19/2021, 5:07 PM
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
5 Views