当可选项为空时如何返回?

新手上路,请多包涵

我喜欢 Java 标准库中的 选项。但是我一直遇到一个基本问题,我还没有想出如何以最好的方式解决(最容易阅读和理解,最漂亮,最短):

当可选项为空时如何从方法返回?

我正在寻找一种通用解决方案,该解决方案适用于选项数量和代码块大小的不同组合。

在以下示例中,我将尝试说明我的意思:

 void m1() {
    // When I get an optional:
    Optional<String> o = getOptional();

    // And want to return if it's empty
    if (!o.isPresent()) return;

    // In the whole rest of the method I have to call Optional.get
    // every time I want the value:
    System.out.println(o.get());

    // Which is pretty ugly and verbose!
}

void m2() {
    // If I instead return null if a value is absent:
    String s = getNullabe();
    if (s == null) return;

    // Then I can use the value directly:
    System.out.println(s);
}

这个问题是关于如何获得上述两个示例的优点:可选类型的安全类型和可为空类型的简洁性。

其余的例子更能说明这一点。

 void m3() {
    // If I on the other hand want to throw on empty that's pretty and compact:
    String s = getOptional()
        .orElseThrow(IllegalStateException::new);

    System.out.println(s);
}

void m4() {
    Optional<String> o = getOptional();
    if (!o.isPresent()) return;

    // I can of course declare a new variable for the un-optionalised string:
    String s = o.get();

    System.out.println(s);

    // But the old variable still remains in scope for the whole method
    // which is ugly and annoying.
    System.out.println(o.get());
}

void m5() {
    // This is compact and maybe pretty in some ways:
    getOptional().ifPresent(s -> {
        System.out.println(s);

        // But the extra level of nesting is annoying and it feels
        // wrong to write all the code in a big lambda.

        getOtherOptional().ifPresent(i -> {
            // Also, more optional values makes it really weird and
            // pretty hard to read,  while with nullables I would
            // get no extra nesting, it would looks good and be
            // easy to read.
            System.out.println("i: " + i);

            // It doesn't work in all cases either way.
        });
    });
}

Optional<String> getOptional() {
    throw new UnsupportedOperationException();
}

Optional<Integer> getOtherOptional() {
    throw new UnsupportedOperationException();
}

String getNullabe() {
    throw new UnsupportedOperationException();
}

如果可选项为空,我如何从方法返回,而不必在方法的其余部分中使用 get ,而无需声明额外的变量并且没有额外的块嵌套级别?

或者,如果无法获得所有这些,那么处理这种情况的最佳方法是什么?

原文由 Lii 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 485
2 个回答

您可以使用 orElse(null)

 String o = getOptional().orElse(null);
if (o == null) {
    return;
}

原文由 dnault 发布,翻译遵循 CC BY-SA 3.0 许可协议

您可以使用 ifPresentmap 方法,如果函数无效并且您需要做副作用,您可以使用 ifPresent -b4,58-

 optional.ifPresent(System.out::println);

如果另一个方法返回依赖于 Optional,那么该方法可能也需要返回 Optional 并使用 map 方法

Optional<Integer> getLength(){
    Optional<String> hi = Optional.of("hi");
    return hi.map(String::length)
}

大多数 时候,当您致电 isPresentget 时,您在滥用 Optional

原文由 Sleiman Jneidi 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题