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

159
Visualizações
Type casting to satisfy multiple type constraints

Is it possible to typecast to satisfy multiple type constraints in kotlin?

Say I have the following case, but want to avoid type casting to class C (in case multiple classes implement A and B, or I don't know type C):

interface A
interface B

class C: A, B

fun <T> foo(bar: T) where T: A, T: B {

}

Is it possible to typecast to A and B simultaneously? Smart cast doesn't seem to allow this. Can I manually cast somehow?

val c = C()
foo(c) // works

val d: Any = c
if (d is A && d is B) {
    foo(d) // smart cast doesn't work here, compiler error
}

// Something like this maybe?
foo(d as A && B)

I know it's possible by creating a new interface that inherits from both A and B, and then use that, but that may not be possible if I don't control the classes in question.

Thanks

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

The type has to explicitly implement the required interfaces and since Any cannot be both B and A (even though it implements both) simultaneously there has to be a third type, like C.

This similar question has a generic work around; Is intersection casting possible in Kotlin?

so arbitrary types T which implement A and B can be recognized as such but is and as can't be directly composed with && which makes it impossible to satisfy your functions type constraints without some kind of explicitly implementing wrapper.

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