Created
April 17, 2018 16:22
-
-
Save lub0s/58a0512a28cbf2abf3f9aa7c9b740dda to your computer and use it in GitHub Desktop.
ordinal of sealed class subclass
This file contains hidden or 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 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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.