Home > Back-end >  T except one class
T except one class

Time:03-08

Suppose I've a class called Devil

class Devil

and I've method called support

fun <T> support(t : T){

}

I want to restrict this function to only accept classes other than Devil (all classes in the world, but not Devil). Something like

fun <T except Devil> support(t : T){

}
  • How do I do this in Kotlin? Is this even possible?

CodePudding user response:

This is very likely an XY problem, so please do not apply this solution without considering something else.

One way to achieve this is to declare a non-generic overload of support() with the explicit type Devil, and deprecate that function with ERROR level:

fun <T> support(t: T) {
    // do your stuff
}

@Deprecated("support() cannot be used with type Devil", level = DeprecationLevel.ERROR)
fun support(devil: Devil) {
    error("NOPE.")
}

Note that this would also exclude subtypes of Devil - why is not explicitly stated in your question, but might be what you want.

However, nothing prevents users from working around it by explicitly specifying a supertype:

support<Any>(Devil()) // compiles fine

Similarly, as @gidds pointed out, this approach also doesn't prevent compilation if you pass in a variable with a static type that is not Devil even if it holds an instance of Devil (because the compiler will choose the generic overload in that case):

val hiddenDevil: Any = Devil()
support(hiddenDevil) // compiles fine
  • Related