Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

130
Views
T except one class

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?
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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 - which is not explicitly stated in your question, but might be what you want.

However, nothing prevents users from working around it by explicitly calling the generic overload by specifying a type in <...>:

support<Devil>(Devil()) // compiles fine
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
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!