Created
November 12, 2021 20:14
-
-
Save SimonMarquis/5843c7f42b71659d48fc7de6eb3d4dab to your computer and use it in GitHub Desktop.
Sealed object instances
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 }, | |
) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fun main() = Sealed::class.sealedObjectInstances() | |
.joinToString(separator = "\n") { it.javaClass.name } | |
.let(::println) | |
// Sealed$SealedObject | |
// Sealed$SealedObject$NestedSealedObject | |
// ExternalSealedObject | |
// Sealed$SubSealed$SubSealedObject |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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