Make Java infer @NotNull for Optional Return Types

徘徊边缘 提交于 2019-12-13 17:02:48

问题


Using Optionals in Java does not protect from NPEs since values still can be null:

Optional<String> myMethod() {
    return null;
}

A way to protect from this at least at runtime is the use of @NotNull annotations. (Not possible at compile time in Java since it does not have non-null references, as opposed to more sophisticated languages like Swift and Kotlin).

Using @NotNull will immediately crash when null is detected, thus preventing null traversing through the program, and making it easier to pinpoint error sources. It's best combined with Unit Tests to make it resilient against breaking due to refactorings.

As far as I can tell, it always makes sense to use @NotNull for Optional return values and parameters.

Now here's the question: Is it somehow possible to make Java infer @NotNull automatically for Optional return values and parameters? I.e. I don't have to write it for every use, but rather have that behaviour by setting some build setting or similar?


回答1:


Optional is not designed to keep only non null values . It may contain null values as well. So your proposal is against the design of the Optional.



来源:https://stackoverflow.com/questions/51878106/make-java-infer-notnull-for-optional-return-types

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!