Skip to content
Advertisement

How to return when an optional is empty?

I love that optionals are in the Java standard library now. But there is one basic problem that I keep running into that I haven’t figured out how to solve in the best way (easiest to read and understand, prettiest, shortest):

How to return from a method when an optional is empty?

I am looking for a general solution that works for different combinations of numbers of optionals and sizes of code blocks.

In the following examples I’ll try to show what I mean:

JavaScript

This question is about how to get the good aspect of both the examples above: The type safely of the optional and the brevity of nullable types.

The rest of the examples illustrates this more.

JavaScript

How can I return from a method if an optional is empty, without having to use get in the rest of the method, without declaring an extra variable and without extra levels of block nesting?

Or if it’s not possible to get all that, what is the best way to handle this situation?

Advertisement

Answer

You could use orElse(null):

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement