3

我确信这在某处得到了回答,但我没有足够好的搜索词来找到它。我正在使用 io.vavr.control.Try 包,当我尝试对结果流中的元素使用 getOrElseThrow 方法时,该方法与 io.vavr.Value 类不明确。我可以指定我想以某种方式使用哪种方法,还是不可能?

在此处输入图像描述

4

3 回答 3

2

您有多种选择:

  • 将显式强制转换添加到所需类型:

    .map(rsp -> rsp.getOrElseThrow((Supplier<NotFoundException>) NotFoundException::new))
    .map(rsp -> rsp.getOrElseThrow((Function<? super Throwable, NotFoundException>) NotFoundException::new))
    
  • 使用 lambda 表达式而不是方法引用:

    .map(rsp -> rsp.getOrElseThrow(() -> new NotFoundException()))
    .map(rsp -> rsp.getOrElseThrow(t -> new NotFoundException(t)))
    
  • 使用外部 lambda 参数的显式类型:

    .map((Value<…&gt; rsp) -> rsp.getOrElseThrow(NotFoundException::new))
    .map((Try<…&gt; rsp) -> rsp.getOrElseThrow(NotFoundException::new))
    
于 2019-10-17T13:25:29.793 回答
2

由于您没有发布完整的代码,我只能对您的外观做出有根据的猜测NotFoundException,但我认为它至少包含以下形式的两个构造函数:

public NotFoundException() {}

public NotFoundException(Throwable cause) {
    super(cause);
}

如果您想将构造函数方法引用与 一起使用Try.getOrElseThrow,则需要通过删除这些构造函数之一(或可能降低可见性)来消除方法引用的歧义,或者回退到使用 lambdas 来构造生成的 throwable。

如果您不能或不想更改NotFoundException类,您可以回退到使用 lambda 而不是方法引用(1 和 2),或者您Function可以Consumer在vavr 函数类型工厂方法:

rsp.getOrElseThrow(cause -> new NotFoundException(cause)); // (1)
rsp.getOrElseThrow(() -> new NotFoundException());         // (2)
rsp.getOrElseThrow(Function1.of(NotFoundException::new));  // (3)
rsp.getOrElseThrow(Function0.of(NotFoundException::new));  // (4)
于 2019-10-15T17:01:16.603 回答
2

You could replace NotFoundException::new with t -> new NotFoundException(t) which will only match the Function argument.

于 2019-10-14T23:45:37.153 回答