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?
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 tonull
as a default value. One should choose wisely based on the service agreements. – Naman