0
votes

I always use nullable types in Kotlin as the returning type of a method when it might return null, but some of thode methods in my Kotlin code can be called from Java as well.

I've just got a NullPointerException in my Java code cause I forgot to check for nullability after calling one of those methods. It wouldn't happen in Kotlin as the compiler would force me to check for that.

What is the proper way to handle this situation? Should I use nullable types as the returning type of my methods only in code used exclusively within Kotlin and always return an Optional in my Kotlin methods which will also be called from Java code?

1
Returning an Optional makes sense in terms of defining the contracts when the value can be absent. On the other hand, if the value must be present when looked up, it can also fallback to null as a default value. One should choose wisely based on the service agreements.Naman
@Naman the value can be null and my method returning type in Kotlin is nullable. The issue is that when calling this method from Java, I don't have the Kotlin compiler to force me to check for nullability.Diego Marin Santos

1 Answers

1
votes

Kotlin will annotate this method with @Nullable in bytecode, and both IDEA and Eclipse (with some extra configuration) should be able to detect the problem. You can increase the severity level to error if you want to make your experience closer to Kotlin (even if not reaching it).

I wouldn't recommend returning Optional from all "nullable" methods for two reasons:

  1. Optional is much less convenient to use than e.g. in Scala.

  2. The libraries you use (including the standard library) don't do it (and may not even use the annotations :( ), so you already need to deal with methods returning null.