Quantcast
Channel: Why should Java 8's Optional not be used in arguments - Stack Overflow
Viewing all articles
Browse latest Browse all 29

Answer by drew for Why should Java 8's Optional not be used in arguments

$
0
0

Let's make something perfectly clear: in other languages, there is no general recommendation against the use of a Maybe type as a field type, a constructor parameter type, a method parameter type, or a function parameter type.

So if you "shouldn't" use Optional as a parameter type in Java, the reason is specific to Optional, to Java, or to both.

Reasoning that might apply to other Maybe types, or other languages, is probably not valid here.

Per Brian Goetz,

[W]e did have a clearintention when adding [Optional], and it was not to be a generalpurpose Maybe type, as much as many people would have liked us to doso. Our intention was to provide a limited mechanism for librarymethod return types where there needed to be a clear way to represent"no result", and using null for such was overwhelmingly likely tocause errors.

For example, you probably should never use it for something thatreturns an array of results, or a list of results; instead return anempty array or list. You should almost never use it as a field ofsomething or a method parameter.

So the answer is specific to Optional: it isn't "a general purpose Maybe type"; as such, it is limited, and it may be limited in ways that limit its usefulness as a field type or a parameter type.

That said, in practice, I've rarely found using Optional as a field type or a parameter type to be an issue. If Optional, despite its limitations, works as a parameter type or a field type for your use case, use it.


Viewing all articles
Browse latest Browse all 29

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>