这是有效的:
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的子类型......
谢谢!
根据Kotlin文档:
默认上限(如果没有指定)是
Any?
这意味着有问题的声明等同于:
fun <A:Any?> nonNullValues(values: List<A?>): List<A> = values.filterNotNull()
Run Code Online (Sandbox Code Playgroud)
该nonNullValues
方法声明返回类型A
为可空项的filterNotNull
列表,而返回类型为非可空项的A
列表.因此不匹配和编译器错误.
归档时间: |
|
查看次数: |
383 次 |
最近记录: |