Search code examples
javanullnon-nullable

Are there plans to add type-checked nullable types to Java?


One of my favorite things about Kotlin, relative to Java, is that you can use the compiler to guarantee that certain values are never null. (Swift also has this feature.)

 var foo: Thing 
 var bar: Thing?

Is that example, foo can never be null. I don't have to pollute my code with of defensive null checks. On the other hand, bar could be null. There is also convenient syntax for checking if something is null and using it.

bar?.x             // bar.x, or null if bar is null
bar ?: defaultBar  // bar, or defaultBar if bar is null
if (bar != null) { 
    // bar is now Thing here, not Thing? (Assuming bar is a parameter or local variable.)
}

Java has been moving faster lately, and adding features, but I haven't heard anything about this. Was it considered and rejected? Or might it someday be added to Java?


Solution

  • No, Oracle has no such plans.

    Oracle feels that you can use a third-party tool to do so, such as the Checker Framework, NullAway, or support built into an IDE such as IntelliJ or Eclipse.

    Oracle doesn't even support the creation of a standard @NonNull annotation that all third-party tools would use. Oracle let JSR 305, which would have defined standard annotations, expire and has not revived it.