java - 如何在 Kotlin 中检查 List 是否包含 null?

标签 java collections kotlin

我无法理解为什么

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/

相关文章:

java - 负前瞻正则表达式直到数字但没有连续的 0

android - 嵌套的 RecyclerView 不滚动

java - 问 : How to set variable which use for if condition

kotlin - 热衷于通过 Kotlin Reflection API 获取无参数构造函数?

java - 有人可以用 java 解释这段代码的答案吗?

java - 我如何继承系统的抗锯齿设置来像 swing 一样将文本绘制到屏幕外的图像上?

java - 使用 HttpClient.Execute(HttpGet) 重定向后获取 URL

python - collections.ChainMap 的目的是什么?

c# - 为什么 HashSet<Point> 比 HashSet<string> 慢这么多?

java - 带有实体键和实体值的 JPA 映射