getResourceAsStream and Nulls


#1

I have this code in Kotlin:

val csvStream: InputStream = this.javaClass.getResourceAsStream(csvFile)
if (csvStream == null) {
    throw IllegalArgumentException("Cannot find CSV File: $csvFile")
}

And I get this warning:

[WARNING] /path/to/CsvMigration.kt: (21, 7) Condition 'csvStream == null' is always 'false'

Why?
getResourceAsStream() can return null; why does Kotlin think it can’t?


#2

Sigh, never mind. I told it that it’s not null. Why couldn’t I notice that before I posted?


#3

Yes if you annotate that class with a @Nullable annotation if should fix this


#4

Nope. The problem is that the getResourceAsStream returns a object of type InputStream! which get’s converted to the non nullable version because of

val csvStream: InputStream = ...

The solution is to switch to either InputStream? or just let the compiler implicitly decide the type.


#5

That would get caught by the compiler you’d get a message like

error: type mismatch: inferred type is InputStream? but InputStream was expected

if you assign a nullable to a nonnullable type


#6

No because this is a java function which returns a platform type.
http://kotlinlang.org/docs/reference/java-interop.html#null-safety-and-platform-types


#7

Yeh then it seems like he should annotate the function with @Nullable because then instead of returning InputStream it would return InputStream?


#8

Yeah, let’s just go through the java standard library and annotate all of the functions with Nullable and NotNull :wink: