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.
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?>
I belive that the answer is List<OutputStream?>
. ?
will make your list can contain null
.
Check the doc: enter link description here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With