Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

131
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda