Home > Blockchain >  Is it possible to provide a generic type constraint to a List in Kotlin?
Is it possible to provide a generic type constraint to a List in Kotlin?

Time:10-13

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

CodePudding user response:

Unfortunately, intersection types are not denotable yet in Kotlin code (see proper autocomplete

  • Related