Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check whether a List contains null in Kotlin?

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.

like image 298
Kalle Richter Avatar asked Jan 27 '23 08:01

Kalle Richter


2 Answers

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

like image 161
s1m0nw1 Avatar answered Jan 31 '23 09:01

s1m0nw1


I belive that the answer is List<OutputStream?>. ? will make your list can contain null. Check the doc: enter link description here

like image 38
ToraCode Avatar answered Jan 31 '23 08:01

ToraCode