Passing Optional.absent() values to methods concis

2020-06-30 17:29发布

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?

3条回答
\"骚年 ilove
2楼-- · 2020-06-30 18:14

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).

foo(Optional.<String>absent())
查看更多
神经病院院长
3楼-- · 2020-06-30 18:24

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?

查看更多
▲ chillily
4楼-- · 2020-06-30 18:29

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.

查看更多
登录 后发表回答