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?
So, this is the right way to do this. If not for anything else, let me at least show it here for my own future reference, for everyone who doesn't read questions, like myself :) Thanks to ColinD (and Alexey).
Just when writing the question, I thought of having
and then the call can look like
Is there a better approach?
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:You can even import these statically to result in cleaner code:
For less common
Optional<>
types, just specify the type argument explicitly. It may not be pretty, but it's correct.