I am writing a kotlin extension function that should only work for sealed classes. Can I define a Generic Constraint - or something similar that serves the same purpose - such that an extension function would only work on classes that are a sealed class?
In my specific example I have an extension function that gets the ordinal of class type within it's sealed class:
inline fun <reified T : Any> T.sealedClassOrdinal() = T::class.sealedClassOrdinal()
inline fun <reified T : Any> KClass<T>.sealedClassOrdinal() =
java.superclass?.classes?.indexOfFirst { sub -> sub == this@sealedClassOrdinal.java } ?: -1
Right now the first extension function can be called on Any
. I would like to scope it down to only extend classes that are of sealed type. The property isSealed
on KClass<T>
exposes that info, but I don't see how to tell the compiler. I want something like this (pseudo code):
inline fun <reified T where T::class.isSealed> T.sealedClassOrdinal() = T::class.sealedClassOrdinal()
and/or
inline fun <reified T : Any> KClass<T>.sealedClassOrdinal() where this.isSealed =
Or any other solution that would achieve such a behavior.