【问题标题】:Try in Vavr with method reference使用方法参考在 Vavr 中尝试
【发布时间】:2020-07-04 12:12:27
【问题描述】:

我正在使用 io.vavr.control.Try 并尝试执行 Try.run 但我不能使用带参数的方法引用。我该如何解决这个问题?

PingRequest pingRequest = new PingRequest();
PingCall pingCall = this.client.newPingCall();
//Try<Void> attempt = Try.run(pinCall::call); //A: this will work if call is a no parameter method
//Try<Void> attempt = Try.run(pinCall.call(pingRequest)); //B: I want to call it with parameter but obvious it can't: Required type: CheckedRunnable
Try<Void> attempt = Try.run(() -> pingCall.call(pingRequest)); //C: Idea pass this way, but I don't know if it's correct
attempt.onSuccess...
public PingResponse call(PingRequest input) throws InternalError {...}

【问题讨论】:

  • 你不能。在这种情况下,您必须依赖 lambda。为了简化您的问题,您要问Runnable r = () -&gt; pingCall.call(pingRequest); 是否可以表示为Runnable r = pingCall::call;。请参阅此相关的Q&Aother Q&A

标签: java java-8 method-reference vavr


【解决方案1】:

如果您首先将值包装在 Try 中,然后将结果值包装在 mapTry 中,则可以使用方法引用,并使用作为方法引用提供的函数:

final Try<PingResponse> responseTry = Try.success(pingRequest)
    .mapTry(pingCall::call);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-10
    • 1970-01-01
    • 2021-07-15
    • 2017-07-19
    • 2012-07-05
    相关资源
    最近更新 更多