简体   繁体   中英

What should be the returning type of a method in Kotlin which value can be null and will be called from Java?

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?

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 eg 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM