简明地将Optional.absent()值传递给方法 [英] Passing Optional.absent() values to methods concisely

查看:1797
本文介绍了简明地将Optional.absent()值传递给方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  //方法声明
public void foo(可选< String> arg);

//编译器错误
foo(Optional.absent());

由于类型推断失败,而是必须显式添加类型:

  //真正的方法调用
foo(可选。< String> absent());

如何避免它?

解决方案

在写这个问题时,我想到了

  public class GuavaConstants {
@SuppressWarnings({raw})
public static final可选的ABSENT = Optional.absent();

//类似于空ImmutableList等。
}

然后调用可以看起来像

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

是否有更好的方法?

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?

解决方案

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?

这篇关于简明地将Optional.absent()值传递给方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆