Inconsistency in null safety

There is a bit of inconsistency from my level of understanding. Let’s say we have code interop with Java, assuming MyJavaClass.getNullString is a static method that returns null:

val s1: String = null // Does not compile, s1 is not nullable
val s2: String = MyJavaClass.getNullString() // Compiles, throws IllegalStateException at runtime

I think it doesn’t make sense to let the second line here to compile. It will be more reasonable to force nullability on a value returned from Java.
Then handling it like this if you don’t want it be nullable:
val s2: String = MyJavaClass.getNullString() ?: ""

If I’m not mistaking this behaviour is well described in this video JVMLS 2015 - Flexible Types in Kotlin - YouTube.

Not really. That would litter your code with a lot of stupid stuff like ?: throw AssertionError("That can't happen")


Paths.get("Foo") ?:  throw AssertionError("Can't happen either")

It would make Java interop very painful. But current situation isn’t great either. I think, Java libraries should be annotated with (possible external) nullability annotations and a tool should exist which will generate those annotations using a bytecode analysis. There would be issues with versions, etc, but it would be an improvement over current situation IMO anyway.

I wanted to say that you should look at KAnnotator, but it has been retired: Could KAnnotator infer @Immutable and @Pure annotations? - #8 by abreslav

Thanks for the video. All it explained is that requiring both null-safety and interop are disasters to start with.