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

Viewed 62
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

1 Answers

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

Related