Skip to content

Instantly share code, notes, and snippets.

@lub0s
Created April 17, 2018 16:22
Show Gist options
  • Save lub0s/58a0512a28cbf2abf3f9aa7c9b740dda to your computer and use it in GitHub Desktop.
Save lub0s/58a0512a28cbf2abf3f9aa7c9b740dda to your computer and use it in GitHub Desktop.
ordinal of sealed class subclass
sealed class Event {
object One : Event()
object Two : Event()
data class Three(val int: Int) : Event()
}
inline fun <reified T : Any> T.ordinal() =
T::class.java.superclass.classes.indexOfFirst { sub -> sub == this@ordinal::class.java }
fun testOrdinal() {
val f = Event.One
val s = Event.Two
val t = Event.Three(123)
val t2 = Event.Three(4444)
println(f.ordinal()) //0
println(s.ordinal()) //1
println(t.ordinal()) //2
println(t2.ordinal()) //2
}
@loeschg
Copy link

loeschg commented Aug 13, 2019

This is a clever solution! One thing worth considering for others that come across this answer: depending on how you scope this, you'll now have an ordinal method available for every class which may not make a whole lot of sense outside of this specific context.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment