为什么此 Koltin 代码会抛出错误类型不匹配:推断类型为 {Comparable<*>? & java.io.Serializable?} 但 Any 是预期的
Why this Koltin code throws error Type mismatch: inferred type is {Comparable<*>? & java.io.Serializable?} but Any was expected
这是我遇到错误的代码:-
有趣的主要(){
val nullList = listOf(1, 3, null, "chair", "table", null)
val nullArrayList = arrayListOf("this", "house", null, 3, 9)
println("This list without the null values is ${nullList.filterNotNull()}")
println("This array without the null values is ${nullArrayList.filterNotNull()}")
}
答案就在问题本身:
在您的问题中,您直接提供了 nullList
和 nullArrayList
的元素列表。由于您没有提供任何类型,它会尝试自动推断数组的类型(这就是推断的意思)。您可以在 IDE 提示中看到这一点:
你可以看到它已经推断出类型:ArrayList<out {Comparable*>? & java.io.Serializale?}>
现在,当您尝试触发时:filterNotNull
它会发现推断类型根本没有可用的方法。
因此,绕过此问题的快速方法是使用 Any?
并让编译器忽略某些错误。长运行中不建议这样做,但目前应该没问题。
解决方案:
fun main(){
val nullList = listOf<Any?>(1, 3, null, "chair", "table", null)
val nullArrayList = arrayListOf<Any?>("this", "house", null, 3, 9)
println("This list without the null values is ${nullList.filterNotNull()}")
println("This array without the null values is ${nullArrayList.filterNotNull()}")
}
这是我遇到错误的代码:-
有趣的主要(){
val nullList = listOf(1, 3, null, "chair", "table", null)
val nullArrayList = arrayListOf("this", "house", null, 3, 9)
println("This list without the null values is ${nullList.filterNotNull()}")
println("This array without the null values is ${nullArrayList.filterNotNull()}")
}
答案就在问题本身:
在您的问题中,您直接提供了 nullList
和 nullArrayList
的元素列表。由于您没有提供任何类型,它会尝试自动推断数组的类型(这就是推断的意思)。您可以在 IDE 提示中看到这一点:
你可以看到它已经推断出类型:ArrayList<out {Comparable*>? & java.io.Serializale?}>
现在,当您尝试触发时:filterNotNull
它会发现推断类型根本没有可用的方法。
因此,绕过此问题的快速方法是使用 Any?
并让编译器忽略某些错误。长运行中不建议这样做,但目前应该没问题。
解决方案:
fun main(){
val nullList = listOf<Any?>(1, 3, null, "chair", "table", null)
val nullArrayList = arrayListOf<Any?>("this", "house", null, 3, 9)
println("This list without the null values is ${nullList.filterNotNull()}")
println("This array without the null values is ${nullArrayList.filterNotNull()}")
}