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

413
Vistas
Is it possible to provide a generic type constraint to a List in Kotlin?
interface Conditional{
   fun isEligible(): Boolean
}

class Super()

class A(): Super(), Conditional
class B(): Super()

I would like to create a list that only contains Super subclasses that have implemented Conditional interface. (Just to help me with some compile-time static type checking)

Compiler would allow me to create this:

val conditionals: List<Super : Conditional> = listOf(A())

But it would not allow me to create this:

val conditionals: List<Super : Conditional> = listOf(A(), B())

I understand you can use generics with classes and function declarations, but how about value declarations?

EDIT I tried the following but type inference doesn't work well, it seems I'd need to do casting to a specific interface enter image description here

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

Unfortunately, intersection types are not denotable yet in Kotlin code (see KT-13108).

However, they are internally supported by the compiler, so you can get away with some generic constructs in some cases.

One option is to use a custom listOf specifically for these types:

fun <T> listOfConditionalSuper(vararg elements: T): List<T> where T: Super, T: Conditional =
    listOf(*elements)

You will get proper type inference then: proper autocomplete

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