我无法理解为什么
class Main {
private val outputStreams: List<OutputStream>
@JvmOverloads constructor(outputStreams: List<OutputStream> = LinkedList()) {
if(outputStreams.contains(null)) {
throw IllegalArgumentException("outputStreams mustn't contain null")
}
this.outputStreams = outputStreams
}
}
导致编译错误...Main.kt:[12,26] Type inference failed. The value of the type parameter T should be mentioned in input types (argument types, receiver type or expected type). Try to specify it explicitly.
.
如果我使用 outputStreams.contains(null as OutputStream))
编译成功,但是 Main(LinkedList<OutputStream>())
由于
kotlin.TypeCastException: null cannot be cast to non-null type java.io.OutputStream
at kotlinn.collection.contains.nulll.check.Main.<init>(Main.kt:12)
at kotlinn.collection.contains.nulll.check.MainTest.testInit(MainTest.kt:13)
这让我没有其他方法可以使代码尽可能接近原始 Java,这是我的意图以及理解这个问题而不是寻找解决方法。
最佳答案
对于编译器,参数outputStreams
不能包含 null
因为它的类型是 List<OutputStream>
而不是 List<OutputStream?>
.类型系统不期望 null
在此列表中,因此无需检查它。
另一方面,如果该参数实际上可以包含null
(因为它来自 Java 调用者)您应该将其显式标记为可为空:List<OutputStream?>
关于java - 如何在 Kotlin 中检查 List 是否包含 null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52719136/