Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

157
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda