Inconsistency in null safety


#1

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() ?: ""
Thoughts?


#2

If I’m not mistaking this behaviour is well described in this video https://youtu.be/2IhT8HACc2E.


#3

Not really. That would litter your code with a lot of stupid stuff like

System.in?.read() ?: throw AssertionError("That can't happen")

or

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

#4

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.


#5

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


#6

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