java 将 Optional.absent() 值简洁地传递给方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11757962/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 06:15:42  来源:igfitidea点击:

Passing Optional.absent() values to methods concisely

javagenericsguava

提问by Alexey Romanov

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

使用 Guava 的Optional类型作为方法参数的一个问题是你不能简单地编写

// 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?

我怎样才能避免它?

采纳答案by Alexey Romanov

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?

有没有更好的方法?

回答by Mike Strobel

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:

如果您正在处理一小组Optional<>类型(例如,主要是字符串或少数其他类型),只需创建一些为您绑定类型参数的辅助方法:

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.

对于不太常见的Optional<>类型,只需明确指定类型参数。它可能不漂亮,但它是正确的。

回答by Sander Verhagen

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

因此,这是执行此操作的正确方法。如果不是为了其他任何事情,至少让我在这里展示它以供我自己将来参考,对于每个不阅读问题的人,例如我自己:) 感谢 ColinD(和 Alexey)。

foo(Optional.<String>absent())