getResourceAsStream and Nulls

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?

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

1 Like

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

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.

1 Like

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

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

1 Like

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

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

1 Like

Yeah, you told it it’s not null right here val csvStream: InputStream. These sort of mistakes are not easily spotted

this.javaClass.getResourceAsStream(csvFile) is nullable

Of course, you can sidestep the whole issue by simplifying the code with the elvis operator:

val csvStream = javaClass.getResourceAsStream(csvFile)
    ?: throw IllegalArgumentException("Cannot find CSV File: $csvFile")