In java when you are working with Optional and you want to pass the value where Optional is not supported you do value = optional.orElse(null)
. This way if the value is present you have it, if the value is absent you have null
.
This is the contrary of optional = Optional.ofNullable(value)
The Optional API has also a orElseGet(..)
method that uses a Supplier
as argument. The difference is not clear to everybody:
The point is, if you are confusing orElse(..)
and orElseGet(..)
, you will use optional.orElseGet(null)
in your code. Its compiles but you get a NullPointerException at runtime.