Skip to content

Instantly share code, notes, and snippets.

@SimonMarquis
Created November 12, 2021 20:14
Show Gist options
  • Save SimonMarquis/5843c7f42b71659d48fc7de6eb3d4dab to your computer and use it in GitHub Desktop.
Save SimonMarquis/5843c7f42b71659d48fc7de6eb3d4dab to your computer and use it in GitHub Desktop.
Sealed object instances
import kotlin.reflect.KClass
fun <T : Any> KClass<T>.sealedObjectInstances() = recursiveSealedObjectInstances()
private tailrec fun <T : Any> KClass<T>.recursiveSealedObjectInstances(
sealedSubclasses: List<KClass<out T>> = listOf(this),
acc: Set<T> = emptySet(),
): Set<T> = when {
sealedSubclasses.isEmpty() -> acc
else -> recursiveSealedObjectInstances(
acc = acc + sealedSubclasses.mapNotNull { it.objectInstance },
sealedSubclasses = sealedSubclasses.flatMap { it.sealedSubclasses },
)
}
fun main() = Sealed::class.sealedObjectInstances()
.joinToString(separator = "\n") { it.javaClass.name }
.let(::println)
// Sealed$SealedObject
// Sealed$SealedObject$NestedSealedObject
// ExternalSealedObject
// Sealed$SubSealed$SubSealedObject
sealed class Sealed {
object SealedObject : Sealed() {
object NestedSealedObject : Sealed()
}
sealed class SubSealed : Sealed() {
object SubSealedObject : SubSealed()
data class DataSubSealed(val any: Any) : SubSealed()
}
}
object ExternalSealedObject : Sealed()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment