Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing Optional.absent() values to methods concisely

One problem with using Guava's Optional type as arguments of methods is that you can't simply write

// method declaration
public void foo(Optional<String> arg);

// compiler error
foo(Optional.absent());

due to type inference failing but instead have to add the type explicitly:

// real method call
foo(Optional.<String> absent());

How can I avoid it?

like image 947
Alexey Romanov Avatar asked Aug 01 '12 11:08

Alexey Romanov


People also ask

What exception is thrown by Optional get () when not nested within Optional isPresent ()?

NoSuchElementException Exception Via orElseThrow() Since Java 10. Using the Optional. orElseThrow() method represents another elegant alternative to the isPresent()-get() pair. Sometimes, when an Optional value is not present, all you want to do is to throw a java.

Can we pass Optional parameters in Java?

There are no optional parameters in Java. What you can do is overloading the functions and then passing default values.

How do you handle Optional empty?

Optional class in Java is used to get an empty instance of this Optional class. This instance do not contain any value. Parameters: This method accepts nothing. Return value: This method returns an empty instance of this Optional class.

Can we use Optional as method parameter?

You should almost never use it as a field of something 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.


1 Answers

If you are dealing with a small set of Optional<> types (e.g., mostly strings or a handful of other types), just create some helper methods that bind the type argument for you:

public final class AbsentValues {
    public static Optional<String> absentString() {
        return Optional.<String>absent();
    }
}

You can even import these statically to result in cleaner code:

import static AbsentValues.*;

...

foo(absentString());

For less common Optional<> types, just specify the type argument explicitly. It may not be pretty, but it's correct.

like image 90
Mike Strobel Avatar answered Nov 17 '22 22:11

Mike Strobel