Explaining Optionals
An Optional
can be thought of as a container that may or may not be empty. As per the API, the container “may or may not contain a non-null
value”. An Optional
is primarily used as a method return type where there is a real need to represent “no result” and when returning null
could cause errors. Before Java 8, programmers would return null
but now, since Java 8, we can return an empty Optional
instead. This has several advantages:
- Reduces the risk of
NullPointerException
s - By using
Optional
as the return type, the API can now clearly state that there may not be a value returned - The
Optional
API facilitates the functional programming style
As well as Optional<T>
, there are Optional
s for the primitive types also; namely: OptionalInt
, OptionalDouble
and OptionalLong
. We will examine them later.
Let us first look at how to create Optional
s.
Creating Optionals
The API provides several static
methods for...