具有泛型类型的Kotlin List上的filterNotNull

Loi*_*oic 4 generics kotlin

这是有效的:

val values: List<String>  = listOf("a", null, "b").filterNotNull()
Run Code Online (Sandbox Code Playgroud)

这不起作用:

fun <A> nonNullValues(values: List<A?>): List<A> = values.filterNotNull()
Run Code Online (Sandbox Code Playgroud)

编译器抱怨泛型类型:

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
Run Code Online (Sandbox Code Playgroud)

这个工作正在:

fun <A: Any> nonNullValues(values: List<A?>): List<A> = values.filterNotNull()
Run Code Online (Sandbox Code Playgroud)

有人可以解释一下为什么我需要告诉编译器A是Any的子类型吗?我认为每种类型都是Any的子类型......

谢谢!

mie*_*sol 6

根据Kotlin文档:

默认上限(如果没有指定)是 Any?

这意味着有问题的声明等同于:

fun <A:Any?> nonNullValues(values: List<A?>): List<A> = values.filterNotNull()
Run Code Online (Sandbox Code Playgroud)

nonNullValues方法声明返回类型A可空项的filterNotNull列表,而返回类型为非可空项的A列表.因此不匹配和编译器错误.