Search code examples
javagenericsguava

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?


Solution

  • Just when writing the question, I thought of having

    public class GuavaConstants {
        @SuppressWarnings( { "raw" })
        public static final Optional ABSENT = Optional.absent();
    
        // similar for empty ImmutableList, etc.
    }
    

    and then the call can look like

    @SuppressWarnings( { "unchecked" })
    foo(GuavaConstants.ABSENT);
    

    Is there a better approach?