Skip to content

Instantly share code, notes, and snippets.

@patrickcousins
Last active January 31, 2020 14:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save patrickcousins/abb3a88298f8fc0f1d7e889a219e05ea to your computer and use it in GitHub Desktop.
Save patrickcousins/abb3a88298f8fc0f1d7e889a219e05ea to your computer and use it in GitHub Desktop.
enumerate the branches of a sealed class up to 2 levels
import kotlin.reflect.KClass
sealed class States {
sealed class StateA : States() {
object One : StateA()
object Two : StateA()
}
sealed class StateB : States() {
object Three : StateB()
object Four : StateB()
sealed class Animals : StateB() {
object Cat: Animals()
object Dog: Animals()
}
}
}
fun main() {
States::class.prettyPrintSealedClass()
States::class.branches().forEach {
println(it)
}
}
fun KClass<*>.prettyPrintSealedClass(recursionLevel: Int = 1) {
if (this.isSealed) {
this.sealedSubclasses.forEach {
println("${createPluses(recursionLevel)} ${it.simpleName}")
if (it.isSealed) {
it.prettyPrintSealedClass(recursionLevel + 1)
}
}
}
}
fun <T: KClass<*>> T.branches():Collection<KClass<*>> {
return this.sealedSubclasses.flatMap {
if (it.isSealed) {
it.branches()
} else {
listOf(it)
}
}
}
fun createPluses(recursionLevel: Int): String {
val stringBuilder = StringBuilder()
for (i in 0 until recursionLevel) {
stringBuilder.append(" +")
}
return stringBuilder.toString()
}
/*
output:
----------------------
States
+ StateA
+ + One
+ + Two
+ StateB
+ + Three
+ + Four
+ + Animals
+ + + Cat
+ + + Dog
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment