FilterNotNull in a Kotlin list with a common type

It works:

val values: List<String>  = listOf("a", null, "b").filterNotNull()

This does not work:

fun <A> nonNullValues(values: List<A?>): List<A> = values.filterNotNull()

The compiler complains about common types:

Error:(8, 63) Kotlin: Type parameter bound for T in fun <T : kotlin.Any> kotlin.collections.Iterable<T?>.filterNotNull(): kotlin.collections.List<T>
 is not satisfied: inferred type A is not a subtype of kotlin.Any

It works:

fun <A: Any> nonNullValues(values: List<A?>): List<A> = values.filterNotNull()

Can someone explain to me why I need to tell the compiler that A is a subtype of Any? I thought each type was a subtype of Any ...

Thank!

+4
source share
1 answer

According to Kotlin docs :

The default upper bound (if not specified) is Any?

This means that a problematic declaration is equivalent to:

fun <A:Any?> nonNullValues(values: List<A?>): List<A> = values.filterNotNull()

nonNullValues A, filterNotNull A. , .

+6

All Articles