How to check whether a List contains null in Kotlin?

Karl Richter :

I'm having trouble understanding why

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
    }
}

causes the compilation error ...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..

If I use outputStreams.contains(null as OutputStream)) the compilation succeeds, but Main(LinkedList<OutputStream>()) fails at runtime due to

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)

which leaves me with no other approach for keeping the code as close to the original Java as possible which is my intend as well as understanding this issue as it is rather than searching for a workaround.

s1m0nw1 :

For the compiler, the parameter outputStreams cannot contain null as its type is List<OutputStream> as opposed to List<OutputStream?>. The type system does not expect null to be inside this list, thus no need to check it.

On the other hand, IF that parameter actually could contain null (since it comes from a Java caller) you should mark it as nullable explicitly: List<OutputStream?>

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=86103&siteId=1