3 ms·
You can annotate Java code with @Nullable annotations. Kotlin will understand it and interop will be safe. Spring does it for example, AFAIK Guava does it as we
by vbezhenar 9y ago
You can annotate Java code with @Nullable annotations. Kotlin will understand it and interop will be safe. Spring does it for example, AFAIK Guava does it as well. It won't work with Scala.
Another advantage over Scala is that Kotlin compiler puts null checks on boundaries between Java and Scala, so even if your code pretending to be safe breaks in runtime, you'll catch error as soon as possible, this null won't leak into your internals to bite you tomorrow.
But that's certainly a thing that could be improved. Majority of Java parameters/return values nullability could be automatically inferred by analyzing bytecode.
- dep_b 9y agoInteresting. A bit worse than Swift and Objective-C. Objective-C has to promise `nonnull` otherwise it's shown as `ObjectType!` which basically means we treat it as non-null but it could be null and can be checked for null. Methods marked `nonnull` can still be nil sometimes, it's just a promise. Hard bugs to fix. Found one in an Apple framework where I could not think of anything else than comparing the address with 0x00000000 to see if it was nil.
- hinkley 9y agoI think you just assume everything in the JDK can return or take null. It's close enough to true.
- vbezhenar 9y agoThat's wrong, a lot of JDK api doesn't return null (and a lot of API throws NPE for null arguments). Assuming that everything can return or take null would make Kotlin code unnecessary verbose. It's a valid approach, but not the most pragmatic one.
- imtringued 9y agoI assume it inserts an automatic nullcheck [1] if you assign the return value of a java method into a non-null kotlin variable. You might still see NPEs but they happen exactly at the interop boundary between java and kotlin. When you do get an NPE the fix is obvious and trivial to implement. With scala the NPE could appear after the null crossed the java/scala boundary deep into scala code where you'd assume it should be impossible to get an NPE. It can sometimes be hard to fix because the problem is far away from the cause. [1] https://kotlinlang.org/docs/reference/java-interop.html#null-safety-and-platform-types https://kotlinlang.org/docs/reference/java-interop.html#null... >If we choose a non-null type, the compiler will emit an assertion upon assignment. This prevents Kotlin's non-null variables from holding nulls. Assertions are also emitted when we pass platform values to Kotlin functions expecting non-null values etc. Overall, the compiler does its best to prevent nulls from propagating far through the program (although sometimes this is impossible to eliminate entirely, because of generics).